单例宏

作者: 闲得一B | 来源:发表于2016-06-22 23:15 被阅读13次

文件名:Singleton.h

// 以后就可以使用interfaceSingleton来替代后面的方法声明
#define interfaceSingleton(name)  +(instancetype)share##name

#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
}
#else
// MRC

#define implementationSingleton(name)  \
+ (instancetype)share##name \
{ \
name *instance = [[self alloc] init]; \
return instance; \
} \
static name *_instance = nil; \
+ (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[super allocWithZone:zone] init]; \
}); \
return _instance; \
} \
- (id)copyWithZone:(NSZone *)zone{ \
return _instance; \
} \
- (id)mutableCopyWithZone:(NSZone *)zone \
{ \
return _instance; \
} \
- (oneway void)release \
{ \
} \
- (instancetype)retain \
{ \
return _instance; \
} \
- (NSUInteger)retainCount \
{ \
return  MAXFLOAT; \
}
#endif

斜杠是为了连接宏
##是为了让后面的name能被替换


实现实例:

#import <Foundation/Foundation.h>
#import "Singleton.h"
@interface Person : NSObject
interfaceSingleton(Person);
@end
#import "Person.h"
@implementation Person
implementationSingleton(Person)
@end

assert();断言

相关文章

  • 单例

    单例 单例宏

  • 单例模式和GCD单例实现

    1、传统单例模式2、GCD单例模式3、用宏实现GCD单例模式4、用宏实现GCD单例模式,名称随类名变化而变化 单例...

  • iOS 单例

    Objective-C 单例宏 Swift 单例声明

  • iOS常用宏

    单例宏

  • iOS 单例

    单例模式实现不能使用继承 定义单例实现 简写 定义单例实现宏

  • 单例 - 宏

  • 单例宏

    文件名:Singleton.h 斜杠是为了连接宏##是为了让后面的name能被替换 实现实例: assert();断言

  • 单例宏

    使用方法: 声明了两个宏 SingleH(name) 和 SingleM(name) 两个宏 创建一个想要实现单例...

  • 单例宏

    使用如下 比如

  • 单例---宏

    // ## : 连接字符串和参数 #define singleton_h(name) + (instancetyp...

网友评论

      本文标题:单例宏

      本文链接:https://www.haomeiwen.com/subject/woyndttx.html