One of my most used design patterns when developing for iOS is the singleton pattern. It’s an extremely powerful way to share data between different parts of code without having to pass the data around manually. More about the singleton pattern and other patterns can be found in this excellent book:
Background
Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.
How to implement
You can implement a singleton class in Objective-C using the following code:
#import "MyManager.h"@implementationMyManager@synthesizesomeProperty;#pragma mark Singleton Methods+(id)sharedManager{staticMyManager*sharedMyManager=nil;staticdispatch_once_tonceToken;dispatch_once(&onceToken,^{sharedMyManager=[[selfalloc]init];});returnsharedMyManager;}-(id)init{if(self=[superinit]){someProperty=[[NSStringalloc]initWithString:@"Default Property Value"];}returnself;}-(void)dealloc{// Should never be called, but just here for clarity really.}@end
What this does is it defines a static variable (but only global to this translation unit)) called sharedMyManager which is then initialised once and only once in sharedManager. The way we ensure that it’s only created once is by using the dispatch_once method from Grand Central Dispatch (GCD). This is thread safe and handled entirely by the OS for you so that you don’t have to worry about it at all.
However, if you would rather not use GCD then you should use the following code for sharedManager:
#import "MyManager.h"staticMyManager*sharedMyManager=nil;@implementationMyManager@synthesizesomeProperty;#pragma mark Singleton Methods+(id)sharedManager{@synchronized(self){if(sharedMyManager==nil)sharedMyManager=[[superallocWithZone:NULL]init];}returnsharedMyManager;}+(id)allocWithZone:(NSZone*)zone{return[[selfsharedManager]retain];}-(id)copyWithZone:(NSZone*)zone{returnself;}-(id)retain{returnself;}-(unsigned)retainCount{returnUINT_MAX;//denotes an object that cannot be released}-(onewayvoid)release{// never release}-(id)autorelease{returnself;}-(id)init{if(self=[superinit]){someProperty=[[NSStringalloc]initWithString:@"Default Property Value"];}returnself;}-(void)dealloc{// Should never be called, but just here for clarity really.[somePropertyrelease];[superdealloc];}@end
转载自http://www.galloway.me.uk/tutorials/singleton-classes/ (稍后过滤一下信息)Singletons in Objective-COne of my most used design patterns when developing for iOS is the singleton pattern. It’s