继承于c语言和c++中的宏定义,oc中也可以方便有效的支持宏定义使用,简单的宏定义谁都知道,比如定义一个int型常量,string类型的字符串都可以。
如果复杂一些呢,比如用宏定义实现单例,实现类的归档操作,其实都是可以的。就以类的归档操作为例,代码说明一下
现有宏定义 SSCodingImplementation定义了一段代码(归档和解档两个方法)
/**
归档的实现
*/
#define SSCodingImplementation \
- (id)initWithCoder:(NSCoder *)decoder \
{ \
if (self = [super init]) { \
[self mj_decode:decoder]; \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)encoder \
{ \
[self mj_encode:encoder]; \
}
接着,有类SSXXXModel,则在其 .m文件中
#import "SSXXModel.h"
@implementation SSXXModel
//自动实现归档,解挡操作
SSCodingImplementation
@end
即可自动实现归档解档代码,原理也很简单,宏定义相当于代表了其后面的一段代码,可以认为就是原封不动将代码拷贝到宏定义所在处。
要注意宏定义复杂形式的写法,在除了最后一行的所有代码行尾加反斜杠 \ ,以表示未结束,下一行仍是宏定义内容。
另附单例的宏定义如下
// @interface
#define singleton_interface(className) \
+ (className *)shared##className;
// @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}
eg: singleton_interface(SSApplication)