What is best way to share class instance (create and share singleton)?
I know 2 ways. What is better? And anything better than 2 ways开发者_如何学JAVA?
+ (MyClass *)shared {
/*
static MyClass *sharedInstance = nil;
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[self alloc] init];
}
}
return sharedInstance;
*/
/*
static dispatch_once_t pred;
static MyClass *sharedInstance = nil;
dispatch_once(&pred, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
*/
}
Can also create a your class instance in AppDelegate
and use it anywhere in your project.
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appappDelegate.<yourClassInstance>
Here is another way to setup you shared instance. Thread safety is handled by the runtime and the code is very straight forward. This is usually how I setup my singletons. If the singleton object uses lots of resources but may not used then the dispatch_once approach works well.
static MyClass *sharedInstance = nil;
+ (void) initialize
{
sharedInstance = [[MyClass alloc] init];
}
+ (MyClass*)sharedInstance
{
return sharedInstance;
}
Just use the dispatch_once version - it's reliable and clean. Besides, it will work also with ARC - unlike the approach suggested above.
Here's some Details
+ (YourClass *)sharedInstance
{
// structure used to test whether the block has completed or not
static dispatch_once_t p = 0;
// initialize sharedObject as nil (first call only)
__strong static id _sharedObject = nil;
// executes a block object once and only once for the lifetime of an application
dispatch_once(&p, ^{
_sharedObject = [[self alloc] init];
});
// returns the same object each time
return _sharedObject;
}
The second one looks better, but this is still not perfect. Check Apple's recommendation:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-97333-CJBDDIBI
精彩评论