1 Preface
Use the dispatch_once function in the app's lifecycle to ensure that each segment of code is executed only once, even if it is called multiple times in different places of the Code (such as single-instance initialization ).
2. code example
Zyappdelegate. m
// An identifier for the dispatch function static dispatch_once_t oncetoken; // block objectvoid (^ executedonlyonce) (void) = ^ {static nsuinteger numberofentries = 0; numberofentries ++; nslog (@ "executed % lu time (s)", (unsigned long) numberofentries) ;};-(bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) launchoptions {// declare a queue whose concurrentqueue = Queue (queue, 0); // execute the queue dispatch_once (& oncetoken, ^ {dispatch_async (concurrentqueue, executedonlyonce );}); dispatch_once (& oncetoken, ^ {dispatch_async (concurrentqueue, executedonlyonce) ;}); self. window = [[[uiwindow alloc] initwithframe: [[uiscreen mainscreen] bounds] autorelease]; // override point for customization after application launch. self. viewcontroller = [[[zyviewcontroller alloc] initwithnibname: @ "zyviewcontroller" Bundle: Nil] autorelease]; self. window. rootviewcontroller = self. viewcontroller; [self. window makekeyandvisible]; return yes ;}
Zyviewcontroller. m
-(Void) viewdidload {[Super viewdidload]; zymysingleton * test = [[zymysingleton alloc] init]; // looping Singleton Method for (INT I = 0; I <5; I ++) {[test sharedinstance];} [test release];}
Zymysingleton. m
-(ID) sharedinstance {static zymysingleton * sharedinstance = nil; // an identifier used to schedule the worker function static dispatch_once_t oncetoken; dispatch_once (& oncetoken, ^ {sharedinstance = [zymysingleton new]; nslog (@ "sharedinstance is =====>%@", sharedinstance) ;}); return sharedinstance ;}
Result displayed on the console after running
17:30:49. 334 gcdsingletest [2717: 1303] executed 1 time (s)
17:30:49. 336 gcdsingletest [2717: c07] sharedinstance is =====> <zymysingleton: 0x7195990>
3 conclusion
The above is all content and I hope it will help you.
DEMO code download: http://download.csdn.net/detail/u010013695/5353668