First, the definition
- Singleton mode: guarantees that a class has only one instance and provides a global access point to access it.
How to guarantee that only one instance can be created
Second, use
- Class can have only one instance, and must be accessed from a well-known access point
- This unique instance can only be extended by subclasses, and the extended object does not break the client code
Third, the Code
- Method One
1 #import "Singleton.h"2 3 @implementationSingleton4 5 StaticSingleton * shared =Nil;6 7+ (Singleton *) Sharedinstance8 {9 Staticdispatch_once_t once;TenDispatch_once (&once, ^{ OneShared =[[Super Allocwithzone:null] init]; A }); - - returnGkfx; the } - -+ (Instancetype) Allocwithzone: (struct_nszone *) Zone - { + return[self sharedinstance]; - } + A @end
Call:
1Singleton * Single =[[Singleton alloc] init];2NSLog (@"%@", single);3 4Singleton * sing =[Singleton sharedinstance];5NSLog (@"%@", sing);6 7Singleton * Single1 =[[Singleton alloc] init];8NSLog (@"%@", single1);9 TenSingleton * Sing1 =[Singleton sharedinstance]; OneNSLog (@"%@", sing1);
Output Result:
Thus, when we call Alloc, we automatically call the + (Instancetype) Allocwithzone: (struct _nszone *) Zone method, call this method when it is called Sharedinstance method, so that whenever this class is used, it is eventually returned by Sharedinstance , and,sharedinstance method, initializes the object only once, So the return address is the same.
1 #import "Singleton.h"2 3 @implementationSingleton4 5 StaticSingleton * shared =Nil;6 7+ (Singleton *) Sharedinstance8 {9 if(Shared = =Nil) {TenShared =[[Self alloc] init]; One } A returnGkfx; - } - the+ (Instancetype) Allocwithzone: (struct_nszone *) Zone - { - Staticdispatch_once_t once; -Dispatch_once (&once, ^{ +Shared =[[Super Allocwithzone:zone] init]; - }); + A returnGkfx; at } - - @end
Method One and method two, the effect is the same, but the function of the execution of the sequence is different, method one regardless of which method is called, the last call is sharedinstance, and method two, regardless of which function is called, the final call is Allocwithzone. The underlying implementations are all the same, and eventually return an address to the static object by [[Super Allocwithzone:zone] init] .
iOS design mode-Singleton mode