Single-instance mode for IOS development

Source: Internet
Author: User

The singleton is that project is only initialized once, saving memory space. or share resources. For example, when creating a Bluetooth class, or to do WiFi communication is often used. can also be used to pass values.

Introduce two ways to create a single case

One, consider the wording of thread safety

/** *  Consider thread-safe notation * *  @return  Modeltool object */+ (instancetype) sharemodel{    static Modeltool *model = nil;    Static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        model = [[Self alloc] init];    });    return model;}

Two, do not consider the thread-safe wording

/** *  do not consider thread-safe notation * *  @return Modeltool object */+ (instancetype) sharemodeltool{    static Modeltool *model = nil;    if (!model) {        model = [[Modeltool alloc] init];    }    return model;}

Three, test these two kinds of wording

-(void) viewdidload {    [super viewdidload];   1.0 consider thread-safe    modeltool *tool1 = [Modeltool Sharemodel];    Modeltool *tool2 = [Modeltool Sharemodel];    Modeltool *tool3 = [Modeltool Sharemodel];    NSLog (@ "tool1 = =%@ Tool2 = =%@ Tool3 =%@", tool1,tool2,tool3);    2.0 do not consider thread safety    modeltool *t1 = [Modeltool sharemodeltool];    Modeltool *t2 = [Modeltool sharemodeltool];    Modeltool *t3 = [Modeltool sharemodeltool];    NSLog (@ "T1 = =%@ T2 = =%@ T3 =%@", t1,t2,t3);}

Four. Print results

2016-03-08 14:26:43.996 Single case design mode [2144:779656] tool1 = = <ModelTool:0x7fb3f1412d20> Tool2 = = <modeltool: 0x7fb3f1412d20> Tool3 = = <ModelTool:0x7fb3f1412d20>     2016-03-08 14:26:43.997 single case design mode [2144:779656] T1 = = <ModelTool:0x7fb3f15263d0> t2 = = <ModelTool:0x7fb3f15263d0> T3 = = <ModelTool:0x7fb3f15263d0>

Both methods guarantee that a piece of memory space is created.


Single-instance mode for IOS development

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.