A single example of the wording, need to use the GCD. As follows:
In. h
@interface*tempstr; /// class method + (Jfsingleton *) sharedinstance; @end
In. m, there are two ways to do this. Dispatch_once is thread-safe and is guaranteed to be called at most once for multiple threads
Method One:
1 @implementationJfsingleton2 3 StaticJfsingleton *_onlyperson =Nil;4 5 ///override this method, which is the method that will eventually be called when allocating memory to an object, ensuring that the memory space is allocated only once6+ (Instancetype) Allocwithzone: (struct_nszone *) zone{7 if(!_onlyperson) {8 Staticdispatch_once_t Oncetoken;//Lock9 //dispatch_once is thread-safe and is guaranteed to be called at most once for multiple threadsTenDispatch_once (&oncetoken,^{ One_onlyperson =[Super Allocwithzone:zone]; A }); - } - return_onlyperson; the } - - //the first time a singleton is used, the Init method is called --(instancetype) init{ + Staticdispatch_once_t Oncetoken; -Dispatch_once (&oncetoken,^{ +_onlyperson =[Super init]; A //Other initialization Operations atSelf.tempstr =@"Firstvalue"; - }); - return_onlyperson; - } - -+ (Jfsingleton *) sharedinstance{ in return[[Self alloc]init]; - } to + @end
Method Two: The method is relatively simple
1 @implementationJfsingleton2 3 StaticJfsingleton *_onlyperson =Nil;4+ (Jfsingleton *) Sharedinstance5 {6 Staticdispatch_once_t Oncetoken;7Dispatch_once (&oncetoken, ^{8_onlyperson =[[Self alloc] init];9 });Ten One return_onlyperson; A } - - //This init method is called when the Singleton is used for the first time. the- (ID) init{ -Self =[Super init]; - if(self) { - //usually do some related initialization tasks here +Self.tempstr =@"Somesth"; - } + returnSelf ; A } at - @end
Simple use of single cases in iOS