Implementation of the OC Singleton mode and the OC Mode
SingleClass. m
# Import <Foundation/Foundation. h> @ class SingleClass; static SingleClass * instance = nil; @ interface SingleClass: NSObject <NSCopying> + (instancetype) using instance; @ end @ implementation SingleClass // class method, obtain the singleton object + (instancetype) using instance {if (! Instance) {instance = [[self alloc] init];} return instance;} // class method. An existing Singleton + (instancetype) is returned when the alloc method of the object is called) allocWithZone :( struct _ NSZone *) zone {if (! Instance) {instance = [super allocWithZone: zone];} return instance;} // copy, returns the existing Singleton-(id) copyWithZone :( NSZone *) zone {return instance;} // copy, returns an existing Singleton-(id) copy {return instance;} @ end
Main. m
int main(int argc, const char * argv[]) { @autoreleasepool { SingleClass *s1 = [SingleClass shareInstance]; SingleClass *s2 = [SingleClass shareInstance]; SingleClass *s3 = [[SingleClass alloc] init]; SingleClass *s4 = [s1 copy]; NSLog(@"%p",s1); NSLog(@"%p",s2); NSLog(@"%p",s3); NSLog(@"%p",s4); } return 0;}
Result:
2015-03-22 22:24:21.201 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e02015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0