Singleton mode is one of the common design patterns in iOS. The role of a singleton design pattern is to make an object of this class the only instance in the system, so it is necessary to create the object in a unique way and return the address of the object. So, when do we use singleton mode? 1. A class can have only one instance, and it must be accessed from a well-known access point. 2. This unique instance can only be extended by subclasses, and the extended object does not break the client code.
So how do you implement a singleton pattern with objective-c? Let's create a new singleton class, implemented in Singleton.h as follows
- @interface Singleton:nsobject
- + (Singleton *) sharedinstance;
- @end
In SINGLETON.M
- @implementation Singleton
- Static Singleton * Sharedsingleton = nil;
- + (Singleton *) sharedinstance
- {
- if (Sharedsingleton = = nil) {
- Sharedsingleton = [[Singleton alloc] init];
- }
- return Sharedsingleton;
- }
- @end
This creates a simple singleton pattern that is actually implemented by some programmers, but in fact it is not a "strict" version, and in practice, it is possible to encounter an object that initiates a call that cannot instantiate a singleton object in another way, or create multiple instances. (Someone has discussed this problem with me before, saying that the user should strictly follow the interface to use, when actually singleton is an object, we can not guarantee that the user will not use other methods to create (such as Alloc), this time he will create multiple instances, This will cause these imperceptible bugs to occur)
Now I'm making improvements to SINGLETON.M.
- @implementation Singleton
- Static Singleton * Sharedsingleton = nil;
- + (Singleton *) sharedinstance
- {
- if (Sharedsingleton = = nil) {
- Sharedsingleton = [[super Allocwithzone:NULL] init];
- }
- return Sharedsingleton;
- }
- + (ID) allocwithzone: (struct _nszone *) zone
- {
- return [[self sharedinstance] retain];
- }
- -(ID) copywithzone: (nszone *) zone
- {
- return self ;
- }
- -(ID) retain
- {
- return self ;
- }
- -(Nsuinteger) Retaincount
- {
- return Nsuintegermax;
- }
- -(void) Release
- {
- //
- }
- -(ID) autorelease
- {
- return self ;
- }
- @end
Maybe you noticed, I overloaded the Allocwithzone: The Singleton object returned from the Sharedinstance method is maintained, and the user returns a unique instance even when using Alloc (the Alloc method calls Allocwithzone: Create object first). and retain and other memory management functions are overloaded, so that we have the Singleton class to become "strict".
Single-instance mode for iOS design mode