"Ios-develop technical article-003" OC Single-case mode

Source: Internet
Author: User

An overview of OC single Example

In iOS development, a singleton is one of the most useful design patterns. It is one of the most useful ways to share data between code without manually passing parameters.

Advantages of the Singleton:

(1) Some things can only have one, that must be used in a single case;

(2) The advantage of a single case is that there will be no redundant instances, so save memory;

(3) Because there is only one singleton, it is easy to manage multi-threaded access to it.

The singleton is an important concept, it is an extremely convenient design pattern. The concept of Singleton is used extensively in the iphone SDK, for example, UIApplication's Sharedapplication method, which returns a uiapplication instance of the current application at any time.

Second, the Code implementation

Use the following code to implement a singleton class:

  MyManager.h

1  #import<foundation/Foundation.h>2  @interfaceMyManager: NSObject3  + (ID) sharedmanager; 4  5  @end

  Mymanager.m

1 #import"MyManager.h"2 @implementationMyManager3 4+(ID) Sharedmanager {5     StaticMymanager*sharedmymanager =Nil;6     StaticDispatch_once_toncetoken;7Dispatch_once (&oncetoken, ^{8Sharedmymanager =[[Self alloc] init];9     });Ten     returnSharedmymanager; One } A @end

We define a static variable called Sharedmymanager, which is only instantiated once in the Sharedmanager method. With GCD's Dispath_once method, we ensure that the Sharedmymanager method is only created once. This is thread-safe and you don't have to worry about anything.

However, if you do not want to use GCG, you can also implement the Sharedmanager method as follows:

1 + (ID) sharedmanager {2    @synchronized (self) {3         If (Sharedmymanager = nil)4            sharedmymanager = [[Self alloc] init]; 5     }6    Returnsharedmymanager; 7 }

This invokes the Singleton object:

Mymanager *sharedmanager = [Mymanager Sharedmanager];

"Ios-develop technical article-003" OC Single-case mode

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.