iOS 單例的標準寫法
阿新 • • 發佈:2018-12-21
.h
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+ (instancetype)shareInstance;
@end
.m
#import "Singleton.h" static Singleton *_instance = nil; @implementation Singleton + (instancetype)shareInstance{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:NULL]init]; }); return _instance; } +(id)allocWithZone:(struct _NSZone *)zone { return [Singleton shareInstance] ; } -(id)copyWithZone:(struct _NSZone *)zone { return [Singleton shareInstance]; } @end