After reading MJ's explanation of the single case of personal summary

Source: Internet
Author: User

1, the introduction of a single case

Singleton is one of the most common development patterns for iOS.

2, what is a single case

A singleton is a class that creates only one object and allocates only one memory space.

3, single case of the application scenario

1) System of single example: [uiapplication sharedapplication];

2) Application of the single example: QQ background map, etc.

4. Precautions for single case

1) always allocate only one piece of memory to create objects

2) provides a class method that returns an internally unique object (one instance)

3) It is best to ensure that the Init method is initialized only once

5, the creation of a single case

1) Overriding the allocation memory method

// override method for allocating memory + (Instancetype) Allocwithzone: (struct _nszone *) zone{    static  dispatch_once_t Once_token;    Dispatch_once (&once_token, ^{        // guaranteed to allocate only once memory        _instance = [ Super Allocwithzone:zone];            });     return _instance;    }

2) Creating a class method

// Create share Method + (instancetype) shareperson{    static  dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{       // is only init once        _instance = [[Self Alloc]init];            });     return _instance;}

3) Overriding the Init method

- (instancetype) init{    if (self = [Super init]) {        static  dispatch_once _t Oncetoken;        Dispatch_once (&oncetoken, ^{            // Assignment, initialize resource         });     return Self ;}

6. Single-instance invocation and output results

1) Invocation of a single case

Person * Mark = [person Shareperson];    person * Mary = [[Person alloc]init];    NSLog (@ "Mark---%p  mary----  %p", mark,mary);

2) output of single case

2016-03-02 21:38:30.743 single[2104:190961] Mark---0x7fe6325488e0  mary----  

After reading MJ's explanation of the single case of personal summary

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.