Singleton mode is a common design pattern in iOS design mode and is intended to ensure that a class has only one instance and provides a global access point to access it. The function of Singleton mode is to solve the problem of "only one instance in application".
A singleton pattern typically encapsulates a static property and provides a way to create a static instance. The following code:
// // Singleton.h// designpatternsdemo//// Created by Han Xuepeng on 15/6/19. // Copyright (c) 2015 Han Xuepeng. All rights reserved. // #import @interface singleton:nsobject+ (Singleton *) Sharemanager; @end
////singleton.m//Designpatternsdemo////Created by Han Xuepeng on 15/6/19.//Copyright (c) 2015 Han Xuepeng. All rights reserved.//#import "Singleton.h"@implementationSingletonStaticSingleton *_sharemanager =Nil;+ (Singleton *) Sharemanager {Staticdispatch_once_t once; Dispatch_once (&once, ^{_sharemanager=[[Self alloc] init]; }); return_sharemanager;}@end
This singleton is still possible if the user is able to use the given method strictly as required, but if you accidentally invoke other methods that can generate the object, the singleton loses its function. Therefore, this single case also needs to be reformed:
1. Rewrite the Allocwithzone method to ensure that the user does not produce new objects when calling Alloc or init.
2. Rewrite the Copywithzone and Mutablecopywithzone methods to ensure that the user does not produce new objects when copying objects.
3, see the situation rewrite retain, Retaincount, Release and Autorelease method. (need to comment out in arc mode)
The re-engineered single example is as follows:
////singleton.m//Designpatternsdemo////Created by Han Xuepeng on 15/6/19.//Copyright (c) 2015 Han Xuepeng. All rights reserved.//#import "Singleton.h"@implementationSingletonStaticSingleton *_sharemanager =Nil;+ (Singleton *) Sharemanager {Staticdispatch_once_t once; Dispatch_once (&once, ^{_sharemanager=[[Self alloc] init]; }); return_sharemanager;}+ (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t once; Dispatch_once (&once, ^{_sharemanager=[Super Allocwithzone:zone]; }); return_sharemanager;}- (ID) Copywithzone: (Nszone *) Zone {return_sharemanager;}- (ID) Mutablecopywithzone: (Nszone *) Zone {return[self copywithzone:zone];}/*Arc Invalid-(ID) retain {return _sharemanager;} -(Nsuinteger) Retaincount {return 1;} -(OneWay void) Release {}-(id) autorelease {return _sharemanager;}*/@end
Test code and input and output results:
ID New ]; ID obj1 = [Singleton Sharemanager]; ID obj2 = [[Singleton alloc] init]; NSLog (@ "obj:%@", obj); NSLog (@ "obj1:%@", obj1); NSLog (@ "obj2:%@", OBJ2);
Output:
-- .- + +: the:27.452designpatternsdemo[24125:607] obj: -- .- + +: the:27.453designpatternsdemo[24125:607] Obj1: -- .- + +: the:27.453designpatternsdemo[24125:607] Obj2:
Attached to this class: single case
A singleton pattern of iOS common design patterns