Objective C - sample Singleton implementation

前端 未结 6 983
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 07:37

*I definitely need a break... cause was simple - array was not allocated... Thanks for help. Because of that embarrassing mistake, I flagged my post in order to delete i

6条回答
  •  别那么骄傲
    2020-12-20 08:33

    The standard way of creating a singleton is like...

    Singleton.h

    @interface MySingleton : NSObject
    
    + (MySingleton*)sharedInstance;
    
    @end
    

    Singleton.m

    #import "MySingleton.h"
    
    @implementation MySingleton
    
    #pragma mark - singleton method
    
    + (MySingleton*)sharedInstance
    {
        static dispatch_once_t predicate = 0;
        __strong static id sharedObject = nil;
        //static id sharedObject = nil;  //if you're not using ARC
        dispatch_once(&predicate, ^{
            sharedObject = [[self alloc] init];
            //sharedObject = [[[self alloc] init] retain]; // if you're not using ARC
        });
        return sharedObject;
    }
    
    @end
    

提交回复
热议问题