iOS Singleton mode

Source: Internet
Author: User

Singleton mode is a kind of common software design pattern.

The singleton mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, thus it is convenient to control the number of instances and save system resources.

If you want to have only one object in a class in the system, Singleton mode is the best solution to the aversion.

The most common singleton in iOS is uiapplication

Single-Instance implementation steps:

1. Overriding the Allocwithzone method

The Allocwithzone method is the method that will eventually be called when the object allocates memory space, overriding the method to ensure that only a memory space is allocated.

2. Set up the Shaerdxxx class method to facilitate other class invocation

+ (ID) Allocwithzone: (struct_nszone *) zone{StaticDemoobj *instance; //dispatch_once is thread-safe, Oncetoken defaults to 0    Staticdispatch_once_t Oncetoken; //Dispatch_once Macros Ensure that the instructions in the block code are executed only onceDispatch_once (&oncetoken, ^{        //in a multithreaded environment, it will only be executed once and instance will only be instantiated onceInstance =[Super Allocwithzone:zone];        }); returninstance;}+(instancetype) shareddemoobj{return[[Self alloc] init];}

There is also a common way to create a singleton:

Static Demoobj *instance; + (instancetype) shareddemoobj{    //  If two threads are instantiated at the same time, it is possible to create two instances to the    if (!  Instance) {        //  thread 1 0x0000a        //  thread 2 0x0000b        instance = [[Self alloc] init];    }     // the pointer returned by the first thread has been modified! }

But the memory addresses of the objects instantiated [[Demoobj alloc] init] and [Demoobj shareddemoobj] are not the same, and the thread is unsafe.

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.