共享类实例(创建和共享单例)的最佳方法是什么?

Cha*_*gUZ 0 iphone singleton shared objective-c ios

我知道两种方式.什么是更好的?什么比两种方式更好?

+ (MyClass *)shared {
    /*
    static MyClass *sharedInstance = nil;

    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
        }
    }
    return sharedInstance;
    */

    /*
    static dispatch_once_t pred;
    static MyClass *sharedInstance = nil;

    dispatch_once(&pred, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
    */ 
} 
Run Code Online (Sandbox Code Playgroud)

His*_*erg 6

AppDelegate可以在项目的任何位置创建您的类实例并在其中的任何位置使用它.

appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

appappDelegate.<yourClassInstance>
Run Code Online (Sandbox Code Playgroud)