Two ways to create a singleton in iOS

Source: Internet
Author: User

Just started to do iOS development, do not know how to create a single case, the search on the internet is mostly not too full, so summed up the two ways to create a single case

First declare the class method in the. h file

1 + (instancetype) sharedutils;

It is then implemented in the. m file, with two ways of implementing it

First, when you create an object, you first determine if you have created the object in the program.

1 Static Publicutils *defaultmanager = nil; 2 3 +(instancetype) sharedutils4{5     if (!  Defaultmanager)6         defaultmanager = [[self allocwithzone:null] init]; 7     8     return Defaultmanager; 9 }

Second, the direct use of the system provides multithreading technology Dispatch_once

1+(instancetype) sharedutils2 {3     Staticpublicutils* _sharedutils =Nil;4     Staticdispatch_once_t _once;5Dispatch_once (&_once, ^{6_sharedutils =[[Self alloc] init];7     });8     9     return_sharedutils;Ten}
Dispatch_once (&_once, ^{});
This multi-threaded role to look at the name estimation is almost the same: for a task to execute and execute only once.

Welcome everyone to make suggestions and comments, we learn together, progress together.

Two ways to create a singleton 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.