Thursday, April 19, 2012

NSAssert in Singleton : why this code is valid?

i don't understand the use of NSAssert in +alloc, as when +alloc is called from +sharedGameManager, the static _sharedGameManager variable is nil (so NSAssert should stop execution the first time [self alloc] init] is called...)



+(GameManager*)sharedGameManager {
@synchronized([GameManager class])
{
if(!_sharedGameManager)
[[self alloc] init];
return _sharedGameManager;
}
return nil;
}

+(id)alloc
{
@synchronized ([GameManager class])
{
NSAssert(_sharedGameManager == nil,
@"Attempted to allocated a second instance of the Game Manager singleton");
_sharedGameManager = [super alloc];
return _sharedGameManager;
}
return nil;
}


Thanks for your answer





No comments:

Post a Comment