专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构
单例
OC 中的单例
static id instance = nil; + (instancetype)sharedManager { static dispatch_once_t onceToken; NSLog(@"%ld", onceToken); dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; } + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [super allocWithZone:zone]; }); return instance; } - (id)copyWithZone:(NSZone *)zone { return instance; }Swift单例class HMSoundTool: NSObject { // 单例 static let sharedSoundTools = HMSoundTool() }OC调用swift需要#import "单例-Swift.h",其中单例为Product Name- 在
Swift中let本身就是线程安全的 在
OC中使用Swift的单例- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { NSLog(@"touchesBegan"); HMNetworkTool *tool = [HMNetworkTool sharedManager]; NSLog(@"tool = %@", tool); HMSoundTool *tool2 = [HMSoundTool sharedSoundTools]; NSLog(@"tool2 = %@", tool2); }