iOS中单例的通用写法

来源:互联网 发布:程序员平均年龄 编辑:程序博客网 时间:2024/05/18 06:24

    iOS中单例的通用写法(在ARC, MRC下可用), 增加了单线程访问限制.


    single.h

    

#import <Foundation/Foundation.h>@interface ToolsMRC : NSObject <NSCopying>+ (instancetype)shareToolsMRC;@end

    single.m

// 考虑MRC优化问题, 防止傻× release单例对象#import "ToolsMRC.h"@implementation ToolsMRCstatic id _instance;+ (instancetype)allocWithZone:(struct _NSZone *)zone {    if (_instance == nil) {        @synchronized(self) {            if (_instance == nil) {                _instance = [super allocWithZone:zone];            }        }    }    return _instance;}+ (instancetype)shareToolsMRC {    if (_instance == nil) {        @synchronized(self) {            if (_instance == nil) {                _instance = [[self alloc] init];            }        }    }    return _instance;}#pragma mark - 重写MRC相关方法- (oneway void)release {    }- (instancetype)retain {    return _instance;}- (NSUInteger)retainCount {    return 1;}- (instancetype)autorelease {    return _instance;}- (id)copyWithZone:(NSZone *)zone {    return _instance;}@end


0 0