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