iOS 宏

记录一些iOS开发中的常用宏,其中有一些宏与网上流传的版本会稍有改动,请仔细查看,欢迎拍砖!

  • block安全调用,当block存在时才调用,支持带参数的block
#define BLOCK_SAFE_INVOKING(block, ...) !block ?: block(__VA_ARGS__)
  • dispatch_once
#define DISPATCH_ONCE(block) static dispatch_once_t onceToken; \
dispatch_once(&onceToken, block)
  • dispatch_async主线程
#define DISPATCH_MAIN_ASYNC(block) dispatch_async(dispatch_get_main_queue(), block)
  • dispatch_async子线程
#define DISPATCH_GLOBAL_ASYNC(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
  • dispatch_semaphore
#define DISPATCH_SEMAPHORE_CREATE dispatch_semaphore_t semaphore = dispatch_semaphore_create(0)
#define DISPATCH_SEMAPHORE_SIGNAL() dispatch_semaphore_signal(semaphore)
#define DISPATCH_SEMAPHORE_WAIT() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
  • 单例
//.h  获取单例的类方法
#define SINGLETON_H(name)   + (instancetype)shared##name;
//.m
#define SINGLETON_M(name) \
static id _instance; \
\
 + (instancetype)shared##name \
{ \
DISPATCH_ONCE(^{\
_instance = [[self alloc] init]; \
});\
return _instance; \
} \
\
 + (instancetype)allocWithZone:(struct _NSZone *)zone \
{ \
DISPATCH_ONCE(^{\
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
 - (id)copyWithZone:(NSZone *)zone \
{ \
return _instance; \
}

你可能感兴趣的:(iOS 宏)