码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 如何创建单例

时间:2014-09-20 17:39:49      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:singleton   objective-c   oc   obj-c   

// YOURCLASSNAME.h

@interface YOURCLASSNAME : NSObject

+(instancetype) sharedInstance;

@end


// YOURCLASSNAME.m

@implementation YOURCLASSNAME

+ (instancetype)sharedXXX {
    static YOURCLASSNAME *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        // alloc & init work
       // [[YOURCLASSNAME alloc] init];
    });

    return _sharedInstance;
}

@end

一个具体的例子如下:(from AFNetWorking framework -> AFNetworkActivityIndicatorManager)

+ (instancetype)sharedManager {
    static AFNetworkActivityIndicatorManager *_sharedManager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedManager = [[self alloc] init];
    });

    return _sharedManager;
}




iOS 如何创建单例

标签:singleton   objective-c   oc   obj-c   

原文地址:http://blog.csdn.net/tounaobun/article/details/39432513

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!