在目标C中使用gcd的调度一次创建单例如果您可以针对IOS 4.0或更高版本使用GCD,它是否是在Object-C(线程安全)中创建单例的最佳方法?+ (instancetype)sharedInstance{
static dispatch_once_t once;
static id sharedInstance;
dispatch_once(&once, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;}
3 回答
RISEBY
TA贡献1856条经验 获得超5个赞
[Foo sharedFoo]
偶然的你
TA贡献1841条经验 获得超3个赞
实例类型
instancetype
Objective-C
+ (instancetype)sharedInstance{ static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^ { sharedInstance = [self new]; }); return sharedInstance;}
+ (Class*)sharedInstance{ static dispatch_once_t once; static Class *sharedInstance; dispatch_once(&once, ^ { sharedInstance = [self new]; }); return sharedInstance;}
慕哥9229398
TA贡献1877条经验 获得超6个赞
@interface MySingleton : NSObject+(instancetype)sharedInstance;+(instancetype)alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));-(instancetype)init __attribute__((unavailable("init not available, call sharedInstance instead")));+(instancetype)new __attribute__((unavailable("new not available, call sharedInstance instead")));-(instancetype)copy __attribute__((unavailable("copy not available, call sharedInstance instead")));@end
@implementation MySingleton+(instancetype)sharedInstance { static dispatch_once_t pred; static id shared = nil; dispatch_once(&pred, ^{ shared = [[super alloc] initUniqueInstance]; }); return shared;}-(instancetype)initUniqueInstance { return [super init];}@end
- 3 回答
- 0 关注
- 555 浏览
添加回答
举报
0/150
提交
取消