iOS开发中一些常用的宏
## //可以链接两个字符
typeof() // 猜测类型
__has_feature(objc_arc) // 判断是否是ARC
#define RGB(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] // 颜色宏
#define RandColor RGB(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255)) // 随机色
EPRECATED_ATTRIBUTE // 当工程中方法过时不推荐或者废弃后又要保留但是又怕其他人员无意中使用,可以用这个宏在方法名字后面分号前面使用
尺寸宏:
#define StatusBar_HEIGHT 20
#define NavigationBar_HEIGHT 44
#define NavigationBarIcon 20
#define TabBar_HEIGHT 49
#define TabBarIcon 30
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
打印宏:
//替换NSLog来使用,debug模式下相当于NSLog,reslease模式下不打印
#ifdef DEBUG
# define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define DLog(...)
#endif
内存宏
//使用ARC和不使用ARC
#if __has_feature(objc_arc)
//compiling with ARC
#else
// compiling without ARC
#endif
#pragma mark - common functions
#define RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
//释放一个对象
#define SAFE_DELETE(P) if(P) { [P release], P = nil; }
#define SAFE_RELEASE(x) [x release];x=nil
系统宏
//获取版本
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#define CurrentSystemVersion [[UIDevice currentDevice] systemVersion]
//获取当前语言
#define CurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
//判断是真机还是模拟器
#if TARGET_OS_IPHONE
//iPhone Device
#endif
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
//检查系统版本
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
注意: 当自定义宏时,一定要加上 "( )" ,否则当外界的运算符优先级高于宏内部时将会出错
例如:
#define NUMBER(x) x+x // 不推荐
#define NUMBER(x) (x+x) // 推荐
NSUInteger sum = NUMBER(5)*2;