Search code examples
objective-csingletonnsassert

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


Solution

  • Are you thinking of NSAssert the wrong way round?

    NSAssert( _sharedGameManager==nil, @"Attempted to …");
    

    Will throw an Exception if _sharedGameManager is not nil. It Asserts that the expression is TRUE, it says "I assert that this must be the case", therefore _sharedGameManager must be nil, or an exception is raised. This could only happen if you tried to create 2 instances of this Class.