Objective-C Singleton Mode
A singleton class is a special class. In a process, only one object of this class exists, and only one object appears in the iOS application. This design pattern is used in many places in the system framework, such as NSFileManager and UIApplication.
- In the ARC environment, the interface file is:
//// DVISingleton. h /// Copyright (c) 2014 Changsha Davy education. All rights reserved. // # import
@ Interface DVISingleton: NSObject + (instancetype) sharedSingleton; @ end
Implementation file:
//// DVISingleton. m /// Copyright (c) 2014 Changsha Davy education. all rights reserved. // # import "DVISingleton. h "@ implementation DVISingleton + (instancetype) sharedSingleton {static DVISingleton * export dobject = nil; // thread security, only the execution of static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// use the allocWithZone of the parent class: method to create the object export dobject = [[super allocWithZone: NULL] init] ;}); return extension dobject ;}- (id) init {if (self = [super init]) {} return self;} + (id) allocWithZone :( struct _ NSZone *) zone {return [self sharedSingleton];} www.bkjia.com-(id) copy {return self;}-(void) dealloc {} @ end
- Implementation files in non-ARC environments:
# Import "DVISingleton. h "@ implementation DVISingleton + (instancetype) sharedSingleton {static DVISingleton * export dobject = nil; // thread security, only the execution of static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// use the allocWithZone of the parent class: method to create the object export dobject = [[super allocWithZone: NULL] init] ;}); return extension dobject ;}+ (id) allocWithZone :( NSZone *) zone {return [[self sharedSingleton] retain];}-(id) copyWithZone :( NSZone *) zone {return self;}-(id) retain {return self;}-(unsigned) retainCount {return UINT_MAX; // denotes an object that cannot be released}-(oneway void) release {// never release}-(id) autorelease {return self;}-(id) init {if (self = [super init]) {} return self ;} -(void) dealloc {[super dealloc];} @ end