iOS single-instance creation

Source: Internet
Author: User

To implement a singleton class in objective-c, you need to do at least the following four steps:

1, for a singleton object to implement a static instance, and initialize, and then set to nil,

2. Implement an instance construction method to check if the static instance declared above is nil, and if it is new and returns an instance of this class,

3, rewrite the Allocwithzone method, to ensure that other people directly use Alloc and Init to try to gain a new strength when the time does not produce a new instance,

4, the appropriate implementation of Allocwithezone,copywithzone,release and Autorelease.

The following is a simple example:

static xylocationmanager *sharedinstance = nil;+  (xylocationmanager *) sharedinstance{    static dispatch_once_t predicate;     Dispatch_once (&predicate, ^{        if  (sharedinstance  == nil)  {             sharedinstance = [[self alloc] init];        }     });        return sharedinstance;} +  (ID) Allocwithzone: (nszone *) zone {        @synchronized ( Self)  {               if  (Sharedinstance == nil)  {             sharedinstance = [super allocwithzone:zone];        }        return  sharedinstance;    }    return nil;} -  (ID) Copywithzone: (nszone *) zone {        return  Self;} -  (ID) init {        @synchronized (self)  {         self = [super init];                return self;    }}



iOS single-instance creation

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.