This article is reproduced to http://blog.csdn.net/remote_roamer/article/details/7107007 1. @implementation Singleton
2.
3. + (Singleton *) Instance {
4. Static Singleton *instance;
5.
6. @synchronized (self) {
7. if (!instance) {
8. Instance = [[Singleton alloc] init];
9.
10.
11.}
12.}
13.
. return instance;
15.}
16.
@end
This singleton can be obtained using [Singleton instance].
Check the following steps at a time:
Line four:
Declares a static variable, and if you have a Java programming background, this might make you a little bit confused, in C (c + + and objective-c), a static local variable scope exists within the function, but the life cycle is the entire program, and the next time the function is called it can still used. (and the class static variables in Java are similar to those shared by each instance variable of the class).
Translator Note: For students with questions about static variables, please click here: http://baike.baidu.com/view/675642.htm
Line sixth:
we want to use thread protection so that at the same time two [Singleton instance] calls do not produce two separate object instances. Even in a single-threaded program, this synchronization does not have a large execution time overhead, and it lays a good foundation for the development of Line seventh:
Check if the class object instance has already been initialized. Whether we need to generate an instance of the class.
14 rows:
Returns the created/existing object instance.