完美单例宏定义(兼容ARC和MRC),项目中可以直接使用

 单例模式:
 1.永远只分配一块内存来创建对象
 2.提供一个类方法, 返回内部唯一的一个对象(一个实例)
 3.最好保证init方法也只初始化一次

写一个宏定义文件,传入宏定义函数名,自动生成符合类名的单例函数名:

ARC下单例的常规写法(代码中的\是宏定义的写法):

static id _instance;
+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (instancetype)shared##name
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
+ (id)copyWithZone:(struct _NSZone *)zone
{
    return _instance; 
}

MRC写法:

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

宏在单例类中的用法(.h文件):

 

宏在单例类中的用法(.m文件):

很明显,极大的精简了单例的写法,提高了代码的复用价值。

具体使用效果:

对象的地址打印:

工作中用到单例,每次重写烦不胜烦。理解了单例的作用和写法,不妨试试这个宏定义,也可以提出修改共同进步

github的下载地址

posted on 2016-08-05 11:58  卢二牛  阅读(439)  评论(0编辑  收藏  举报

导航