iOS开发——C预处理器篇

2018-09-11  本文已影响0人  本本的开心牧场

首先介绍一下简介
C 预处理器不是编译器的组成部分,但是它是编译过程中一个单独的步骤。简言之,C 预处理器只不过是一个文本替换工具而已,它们会指示编译器在实际编译之前完成所需的预处理,简写为 CPP。
所有的预处理器命令都是以井号(#)开头。它必须是第一个非空字符,为了增强可读性

常用预处理器指令

在iOS开发中常用
#ifdef 判断IDE环境

#ifdef DEBUG // 处于开发阶段
#define ATLog(...) NSLog(__VA_ARGS__)
#else // 处于发布阶段
#define ATLog(...)
#endif

#ifndef #ifdef的!版本

//防止头文件重复导入
#ifndef Sheet_h
#define Sheet_h
#endif

#if 类似于if 但是一般用于判断IDE环境

#if TARGET_OS_IOS || TARGET_OS_TV

#pragma 在iOS中一般用于代码分成逻辑区块

//这个很熟悉吧
#pragma mark

#define 这个概念不解释了

#define print(...) printf(__VA_ARGS__)
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define weakify(...) \\ autoreleasepool {} \\ metamacro_foreach_cxt(rac_weakify_,, __weak, __VA_ARGS__)

甚至可以用宏定义一个单例

// .h文件
#define ATSingletonH(name) + (instancetype)shared##name;

// .m文件
#if __has_feature(objc_arc)

#define ATSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
}

#else

#define ATSingletonM(name) \
static id _instace; \
\
+ (id)allocWithZone:(struct _NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [super allocWithZone:zone]; \
}); \
return _instace; \
} \
\
+ (instancetype)shared##name \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instace = [[self alloc] init]; \
}); \
return _instace; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return _instace; \
} \
\
- (oneway void)release { } \
- (id)retain { return self; } \
- (NSUInteger)retainCount { return 1;} \
- (id)autorelease { return self;}

#endif
上一篇 下一篇

猜你喜欢

热点阅读