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