浅谈——用宏封装单例

来源:互联网 发布:sql 注入 php 提权 编辑:程序博客网 时间:2024/06/15 22:15

//

//  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

0 0
原创粉丝点击