suppose I got a singleton class MySingleton as coded below.
Now is a singleton class just like any other class. I can have instance variables that are nonatomic and retain?
I can have: @property (nonatomic, retain) NSString* instanceVar in the .h file
and @synthesize instanceVar in the .m file?
static MySingleton* _sharedMySingleton = nil;
+(MySingleton*)sharedMySingleton
{
@synchronized([MySingleton class])
{
if (!_sharedMySingleton)
[[self alloc] init];
return _sharedMySingleton;
}
return nil;
}
+(id)alloc
{
@synchronized([MySingleton class])
{
NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
_sharedMySingleton = [super alloc];
return _sharedMySingleton;
}
return nil;
}
dispatch_onceinstead@synchronized, it's 20x faster. - Jano