Simple use of single cases in iOS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.