iOS单例写法

来源:互联网 发布:linux history 记录数 编辑:程序博客网 时间:2024/05/20 11:50

在Java中有三种写法

单例第一种写法,普通写法:

+ (instancetype)shareSingleton{    static Singleton *singleton = nil;    if(!singleton){        singleton = [[Singleton alloc] init];    }    return singleton;}

在iOS4.0之后的写法

- (instancetype)shareSingleton{    static Singleton * singleton = nil;    dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        singleton = [[Singleton alloc] init];    });}

经过一系列学习,发现还有一种写法,与大家分享:
ARC下:

+ (instancetype)shareSingleton{    static Singleton *singleton = nil;    @synchronized(self) {        singleton = [[super allocWithZone:nil] init];    }    return singleton;}//防止有程序绕过alloc 所以调用 allocWithZone 返回单例方法+ (instancetype)allocWithZone:(struct _NSZone *)zone{    return [self shareSingleton] ;}// 当第一次使用这个单例时,会调用这个init方法。- (id)init{   self = [super init];    if (self) {        // 通常在这里做一些相关的初始化任务    }    return self;}

如果在MRC下:
还需要重写一下:

// 这个dealloc方法永远都不会被调用--因为在程序的生命周期内容,该单例一直都存在。(所以该方法可以不用实现)-(void)dealloc{   [super dealloc];}// 同样,不希望生成单例的多个拷贝。- (id)copyWithZone:(NSZone *)zone {    return self;}// 什么也不做——该单例并不需要一个引用计数(retain counter)- (id)retain {    return self;}// 替换掉引用计数——这样就永远都不会release这个单例。- (NSUInteger)retainCount {    return NSUIntegerMax;}// 该方法是空的——不希望用户release掉这个对象。- (oneway void)release {}//除了返回单例外,什么也不做。- (id)autorelease {    return self;}

如有错误地方请一定告知!谢谢!

1 0
原创粉丝点击