OC 设计模式——单例模式

单例模式的作用:可以保证在程序运行过程,一个类只有一个实例,而且这个实例易于供外界访问。永远只分配一次内存给这个类。由于在调用alloc方法的时候,都会调用allocWithZone,所以要重写这个方法,保证只分配一次内存。 dispatch_once这个方法可以保证只调用一次,并且会自动加锁,线程安全。
在6.0之前的版本中修改工程为非ARC

Xcode6.3下设置,修改工程在非ARC下:

定义宏来实现单例的通用性。在拼接宏的时候不能使用注释。最后面不能加/.

// ## : 两个#号连接字符串和参数
#define singleton_h(name) + (instancetype)shared##name;

#define singleton_m(name) \
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; \
}

调用举例:

- (id)init

{

    if (self = [super init]) {

        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            // 加载资源

            

        });

    }

    return self;

}

 

singleton_m(NetTool)

重写init方法。调用单例的宏。

 

 

如何实现ARC与非ARC下的单例宏,兼容?(添加条件编译进行判断)

 

posted @ 2015-07-10 19:06  Qingyun_Qearl  阅读(278)  评论(0编辑  收藏  举报