To implement a singleton, the key is to ensure that the class's alloc and Init are called only once and are strongly referenced by themselves to prevent release.
Recently read Mr. Tang Qi "iOS development Advanced", benefited, through the GCD to achieve a single case is one of the harvest, the following to share this method with you.
In GCD, there is a function dispatch_once, you can implement a one-time code snippet execution, and static modified variable assignment, we combine static and dispatch_once, we can simply implement a singleton.
The following code implements the SomeClass single example:
#import <Foundation/Foundation.h> @interface someclass:nsobject+ (SomeClass *) sharedinstance; @end
#import "SomeClass.h" @implementation someclass+ (SomeClass *) sharedinstance{ static id sharedinstance = nil; Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ sharedinstance = [[Self alloc] init]; }); return sharedinstance; } @end
This code is explained below.
The first sentence creates a sharedinstance static strong pointer to point to the created Singleton, preventing it from being released, and the pointer is assigned nil only when the first entry is made.
The second and dispatch_once are fixed usages, so that the code within the block can be executed once, that is, the class is instantiated only the first time the method is called, and then the value that the pointer points to is returned.
Finally, a pointer is returned, which is equivalent to getting a singleton.
Verify the results of the single-instance operation:
We get the Singleton object multiple times and print the address, and we can see that the address is the same.
#import "ViewController.h" #import "SomeClass.h" @interface Viewcontroller () @end @implementation viewcontroller-(void ) Viewdidload { [super viewdidload]; SomeClass *SC1 = [SomeClass sharedinstance]; SomeClass *SC2 = [SomeClass sharedinstance]; SomeClass *SC3 = [SomeClass sharedinstance]; NSLog (@ "%p%p%p", SC1,SC2,SC3); } @end
2015-08-17 20:59:22.139-based GCD implementation of the single case [2785:31918] 0x7fb40af11b90 0x7fb40af11b90 0x7fb40af11b90
In this way, simple and efficient implementation of a single case, it is worth using.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
(123) GCD-based dispatch_once implementation of single-case design