简体   繁体   中英

“Pro Objective-C Design Patterns for iOS” subclassing Singleton confusion

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM