IOS Design Pattern singleton: iOS Design Pattern
The Singleton Mode means that this class has only one instance, and this class is a singleton class. In iOS, many of them are Singleton NSNull, NSFileManager, UIApplication, NSUserDefaults, UIDevice, and some third parties can also use this design pattern, such as Afhttpmanger...
(1) Singleton mode: This mode ensures that there is only one instance in a class during the program running, and the instance is easy for external access, so as to conveniently control the number of instances, and saves system resources.
(2) single-instance mode: Share a resource in the entire application (this resource only needs to be created and initialized once ), this class should always have only one object.
Implementation ideas:
//// AudioPlayer. m // Singleton /// Created by two good three bad on 16/2/21. // Copyright©2016 ;. all rights reserved. // # import "AudioPlayer. h "@ interface AudioPlayer () <NSCopying> @ end @ implementation AudioPlayer // create a Global static instance static id _ instance; // provides one class method for external access to a unique instance + (instancetype) Audio audioplayer {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [[self alloc] init] ;}); return _ instance ;}// rewrite allocWithzone: Method to Control Memory allocation. Because alloc calls this method internally, the system creates a new memory space each time it calls allocWithzone: method. + (Instancetype) allocWithZone :( struct _ NSZone *) zone {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instance = [super allocWithZone: zone];}); return _ instance;} // implement copyWithZone: method-(id) copyWithZone :( NSZone *) zone {return _ instance;} @ end
In the control, create an object for the singleton class. Print the address:
-(Void) viewDidLoad {[super viewDidLoad]; AudioPlayer * player1 = [AudioPlayer audio AudioPlayer]; AudioPlayer * player2 = [[AudioPlayer alloc] init]; audioPlayer * player3 = [AudioPlayer new]; AudioPlayer * player4 = [player1 copy]; NSLog (@ "% p, % p", player1, player2, player3, player4);} // print the result 23:27:13. 990 Singleton [2847: 329685] 0x7fb6e3e080a0, 0x7fb6e3e080a0, 0x7fb6e3e080a0, 0x7fb6e3e080a0
The memory addresses of the four instances are the same, proving that only one instance is created;
In the MRC environment, we usually need to implement the following methods:
- (oneway void)release {}- (id)retain { return _instance; }- (id)autorelease { return _instance; }- (NSUInteger)retainCount { return UINT_MAX; }
You can use a macro to determine whether it is mrc,
#if __has_feature(objc_arc) // ARC #else // MRC #endif
Of course, you can also extract a singleton as a macro, which is quite convenient to use. You can also try it ~~~