Programming with singleton mode in iOS

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.