您好我有iOS版的一個單例的實現以前的版本如下:iOS 5中的單身?
.h文件中
@interface CartSingleton : NSObject
{
}
+(CartSingleton *) getSingleton;
.m文件
@implementation CartSingleton
static CartSingleton *sharedSingleton = nil;
+(CartSingleton *) getSingleton
{
if (sharedSingleton !=nil)
{
NSLog(@"Cart has already been created.....");
return sharedSingleton;
}
@synchronized(self)
{
if (sharedSingleton == nil)
{
sharedSingleton = [[self alloc]init];
NSLog(@"Created a new Cart");
}
}
return sharedSingleton;
}
//==============================================================================
+(id)alloc
{
@synchronized([CartSingleton class])
{
NSLog(@"inside alloc");
NSAssert(sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
sharedSingleton = [super alloc];
return sharedSingleton;
}
return nil;
}
//==============================================================================
-(id)init
{
self = [super init];
}
但是網絡我看到人們已實施使用此代碼的Singleton設計模式:
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
有經驗的人請指導我。 我是一個新手,徹底混淆了Singleton和舊的iOS的舊的實現,哪個是正確的?
非常感謝
見http://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c更現代的,更簡單但仍然線程安全。 – 2012-01-09 23:18:47