iOS 宏

作者: 起个名字想破头 | 来源:发表于2017-07-10 12:05 被阅读21次

记录一些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 宏

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