Objective-c Declaration of single-instance classes

Source: Internet
Author: User

In objective-C, the process for defining a singleton class is as follows:

1. Define a static class object. The initial value is nil.

2. In the factory method (generally named "sharedinstance" or "sharedmanager"), use allocwithzone only if the static Class Object declared in the first step is empty: method to create a new object

3. Override allocwithzone: Method

4. Add a memory management method to ensure that only one instance of this class will appear.

The following is an official demo of Apple:

# Import "mysingletonclass. H "@ implementation mysingletonclass // 1. Declare a static class object static mysingletonclass * sharedgizmomanager = nil; // 2. Create a factory method + (mysingletonclass *) sharedmanager {@ synchronized (Self) {If (sharedgizmomanager = nil)Sharedgizmomanager = [[Super allocwithzone: NULL] init];} return sharedgizmomanager;} // 3. memory management method to ensure that the memory counter is in the memory when the object exists in the memory, the retaincount value of this object is always 1 + (ID) allocwithzone :( nszone *) Zone {return [[self sharedmanager] retain];}-(ID) copywithzone :( nszone *) zone {return self;}-(ID) Retain {return self;}-(nsuinteger) retaincount {return nsuintegermax; // denotes an object that cannot be released}-(ID) autorelease {return self;} @ end

Related Article

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.