在目标C中使用gcd的调度一次创建单例

在目标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;}


呼唤远方
浏览 501回答 3
3回答

RISEBY

这是一种完全可以接受和线程安全的方法来创建类的实例。从技术上讲,它可能不是“单例”(因为只有一个这样的对象),但是只要您只使用[Foo sharedFoo]方法来访问对象,这就足够了。

偶然的你

实例类型instancetype的许多语言扩展之一。Objective-C,每个新版本都会添加更多内容。知道了,爱死了。并以它为例,说明如何关注低层次的细节可以让你洞察到转变目标C的强大的新方法。请参阅此处:instancetype+ (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

MySingleton.h@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")));@endMySingleton.m@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
打开App,查看更多内容
随时随地看视频慕课网APP