您的位置:首页 > 其它

浅谈——用宏封装单例

2015-09-24 00:14 330 查看
//

// Single.h

// 单例模式

//

// Created by lisilong on 15/8/18.

// Copyright © 2015年 longshao. All rights reserved.

//

// 判断当前是否时ARC

// 注意点:

// 1.单例是不可以继承的,
如果继承引发问题

// * 如果先创建父类,
那么永远都是父类

// * 如果先创建子类,
那么永远都是子类

// 说明:

// 1.调用allocWithZone:方法,给对象分配内存空间;

// 2.retainCount方法返回-1,或无限大MAXFLOAT只是让别的程序员一块便知道你这是一个单利对象。

/** 类的声明部分 */

#define SingleInterface(name) + (instancetype)share##name

/** 类的实现部分 */

#if __has_feature(objc_arc)

// ARC

#define SingleImplement(name) + (instancetype)share##name \

{ \

return [[self alloc] init]; \

} \

+ (instancetype)allocWithZone:(struct _NSZone *)zone \

{ \

static id instance; \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

instance = [super allocWithZone:zone]; \

}); \

return instance; \

} \

- (nonnull id)copyWithZone:(nullable NSZone *)zone \

{ \

return self; \

} \

- (id)mutableCopyWithZone:(nullable NSZone *)zone \

{ \

return self; \

}

#else

// MRC

#define SingleImplement(name) + (instancetype)share##name \

{ \

return [[self alloc] init]; \

} \

+ (instancetype)allocWithZone:(struct _NSZone *)zone \

{ \

static id instance; \

static dispatch_once_t onceToken; \

dispatch_once(&onceToken, ^{ \

instance = [super allocWithZone:zone]; \

}); \

return instance; \

} \

- (nonnull id)copyWithZone:(nullable NSZone *)zone \

{ \

return self; \

} \

- (id)mutableCopyWithZone:(nullable NSZone *)zone \

{ \

return self; \

} \

- (oneway void)release \

{} \

- (instancetype)retain \

{ \

return self; \

} \

-(NSUInteger)retainCount \

{ \

return MAXFLOAT; \

}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: