Question

I did not understand a question, I test the following two methods to create a subclass instance, the results were running well. For example SingletonSon: Singleton, sub-class without any modification, when you call [SingletonSon sharedInstance] or [SingletonSon alloc] returns an instance is SingletonSon instead of Singleton. Contrary to the results with the original content in book, the original said:if not modified subclass Singleton, always returns an instance of Singleton.

    +(Singleton *) sharedInstance  
    {  
       if(sharedSingleton==nil)  
       {  
          sharedSingleton=[[super allocWithZone:NULL] init];  
       }  
       return sharedSingleton;  
    }

    +(Singleton *) sharedInstance  
    {  
       if(sharedSingleton==nil)  
       {  
          sharedSingleton=[NSAllocateObject([self class],0,NULL) init];  
       }  
       return sharedSingleton;  
    }

I am a Chinese student, my English is not very good, hope forgive me. Looking forward to your answer.

Was it helpful?

Solution

Well, I'd remove the "Pro", because the code isn't thread safe at all. Here is the generally accepted pattern to create a singleton:

+(Singleton *)sharedSingleton {

    static dispatch_once_t once;
    static Singleton *sharedSingleton;
    dispatch_once(&once, ^{
        sharedSingleton = [[self alloc] init];
    });
    return sharedSingleton;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top