Objective-C in IOS: learning the singleton mode in ARC, iosobjective-c
The Singleton mode is a commonly used design mode. The most common purpose is to save and transmit data. This is due to the features of the singleton mode. First, let me briefly introduce the features of Singleton mode.
Three features of Singleton mode:
1. A class can only have one instance;
2. It must create the instance on its own;
3. It must provide this instance to the entire system.
The Code is as follows:
MySingleton. h
# Import <Foundation/Foundation. h>
@ Interface mySingleton: NSObject
+ (MySingleton *) sharedInstance;
@ End
MySingleton. m
# Import "mySingleton. h"
Static mySingleton * myst = nil;
@ Implementation mySingleton
+ (MySingleton *) sharedInstance {
If (myst = nil ){
Static dispatch_once_t once;
Dispatch_once (& once, ^ {
Myst = [[super allocWithZone: NULL] init];
});
}
Return myst;
}
+ (Id) allocWithZone :( struct _ NSZone *) zone {
Return [mySingleton sharedInstance];
}
-(Id) copy {
Return [mySingleton sharedInstance];
}
@ End
This mySingleton class is created with a static modified myst global instance, which is a singleton instance.
Implementation Method:
-(Void) viewDidLoad {
[Super viewDidLoad];
MySingleton * s1 = [mySingleton sharedInstance];
MySingleton * s2 = [[mySingleton alloc] init];
MySingleton * s3 = [s1 copy];
NSLog (@ "s1 =%@", s1 );
NSLog (@ "s2 = % @", s2 );
NSLog (@ "s3 =%@", s3 );
}
Running result:
S1 = <mySingleton: 0x7fbea8e05d70>
S2 = <mySingleton: 0x7fbea8e05d70>
S3 = <mySingleton: 0x7fbea8e05d70>
The running result shows that the addresses of the objects generated by the three different methods are the same.