iOS单例写法

写法1:

实现文件:GCD

@implementation NewObject

static NewObject *_instance = nil;

+ (instancetype)shareInstance {
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       _instance = [[super allocWithZone:NULL] init];
   });
    
   return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
   return [NewObject shareInstance];
}

- (id)copyWithZone:(struct _NSZone *)zone {
   return [NewObject shareInstance];
}

- (id)mutableCopyWithZone:(struct _NSZone *)zone {
   return [NewObject shareInstance];
}

@end

写法2:

static A *_instance;

@implementation A

+ (instancetype)shared {
    
    @synchronized(self) {
        if (!_instance) {
            _instance = [[super allocWithZone: NULL] init];
        }
    }
    return _instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [A shared];
}

- (id)copyWithZone:(struct _NSZone *)zone {
    return [A shared];
}

- (id)mutableCopyWithZone:(struct _NSZone *)zone {
    return [A shared];
}

@end

你可能感兴趣的:(iOS单例写法)