首页 > 其他 > 详细

单例模式ARC和非ARC

时间:2015-09-10 15:46:04      阅读:251      评论:0      收藏:0      [点我收藏+]

ARC环境下的单例模式:

static id _instance = nil; 
+ (id)allocWithZone:(struct _NSZone *)zone 
{ 
    if (_instance == nil) { 
         
        static dispatch_once_t onceToken; 
         
        dispatch_once(&onceToken, ^{ 
            _instance = [super allocWithZone:zone]; 
        }); 
         
    } 
     
    return _instance; 
     
} 
 
- (id)init 
{ 
     
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        _instance = [super init]; 
    }); 
    return _instance; 
} 
 
+ (instancetype)sharedMethodName
{ 
    return [[self alloc] init]; 
}

非ARC模式下的单例模式:

static id _instance = nil; 
+ (id)allocWithZone:(struct _NSZone *)zone 
{ 
    if (_instance == nil) { 
         
        static dispatch_once_t onceToken; 
         
        dispatch_once(&onceToken, ^{ 
            _instance = [super allocWithZone:zone]; 
        }); 
         
    } 
     
    return _instance; 
     
} 
 
- (id)init 
{ 
     
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
        _instance = [super init]; 
    }); 
    return _instance; 
} 
 
+ (instancetype)sharedMethodName
{ 
    return [[self alloc] init]; 
} 
 
- (oneway void)release 
{ 
     
} 
 
- (id)retain 
{ 
    return self; 
} 
 
- (NSUInteger)retainCount 
{ 
    return 1; 
}

如何判断当前的环境是arc还是非arc  可以这样写:

#if __has_feature(objc_arc)  //是arc

//这里写arc下的代码

#else           //非arc

//这里写非acr下的代码

#endif

单例模式ARC和非ARC

原文:http://www.cnblogs.com/syios/p/4797783.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!