#import <Foundation/Foundation.h> @interface danli:nsobject<nscopying,nsmutablecopying>@ End@implementation danli+ (instancetype) sharedanli{ Static Danli * dan; Static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ if (dan = = nil) { Dan = [[Super Allocwithzone:nil] init]; } ); return Dan;} + (ID) allocwithzone: (struct _nszone *) zone{ return [Danli Sharedanli];} -(ID) Copywithzone: (Nszone *) zone{ return [Danli Sharedanli];} -(ID) Mutablecopywithzone: (Nszone *) zone{ return [Danli Sharedanli];} @end
Potential problems with a singleton pattern
1. Memory Issues
The singleton pattern actually extends the life cycle of the object. Then there is a memory problem. Because this object exists throughout the life of the program. So when this single case is relatively large, always hold so much memory, you need to consider this matter. In addition, it is possible that the singleton itself is not large, but it is a problem if it strongly references another larger object. Other objects are not freed because the singleton object is not freed.
Of course, there are certain ways of this problem. For example, for some objects that can be reloaded and loaded when needed, the singleton object will no longer be strongly referenced, thus releasing the previously holding object (set to nil). The next time you need to load it back.
2. Cyclic dependency issues
In the development process, the singleton object may have some attributes, which are typically created and initialized at the time of Init. Thus, for example, if the M property of a singleton is dependent on the Singleton B, and the attribute N of the singleton B depends on the singleton A, the initialization time will be dependent on the dead loop. died in the dispatch_once.
The best design is when a singleton is designed, the content of the initialization does not depend on other objects. If you really want to rely on, do not let it form a ring. It can actually form a loop or cannot be controlled, and it takes the form of asynchronous initialization. Go ahead and fill in the content later. The internal need to make a logo, the identification of the singleton after the creation, not immediately use or complete use.
IOS-Singleton class