Skip to content

Instantly share code, notes, and snippets.

@wenghengcong
Last active July 11, 2019 12:08
Show Gist options
  • Select an option

  • Save wenghengcong/5340178560876cb97708613a45955f6e to your computer and use it in GitHub Desktop.

Select an option

Save wenghengcong/5340178560876cb97708613a45955f6e to your computer and use it in GitHub Desktop.
宏和关键字
1. 主线程安全执行- source:SDWebImage
dispatch_main_async_safe
#ifndef dispatch_main_async_safe
#define dispatch_main_async_safe(block)\
if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(dispatch_get_main_queue())) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
#endif
2. 信号量-加锁解锁- source:SDWebImage
#ifndef SD_LOCK
#define SD_LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
#endif
#ifndef SD_UNLOCK
#define SD_UNLOCK(lock) dispatch_semaphore_signal(lock);
#endif
使用
dispatch_semaphore_t failedURLsLock = dispatch_semaphore_create(1);
BOOL isFailedUrl = NO;
SD_LOCK(self.failedURLsLock);
isFailedUrl = [self.failedURLs containsObject:url];
SD_UNLOCK(self.failedURLsLock);
@weakify(self);
@strongify(self);
#ifndef weakify
#define weakify(...) \
sd_keywordify \
metamacro_foreach_cxt(sd_weakify_,, __weak, __VA_ARGS__)
#endif
#ifndef strongify
#define strongify(...) \
sd_keywordify \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
metamacro_foreach(sd_strongify_,, __VA_ARGS__) \
_Pragma("clang diagnostic pop")
#endif
#define sd_weakify_(INDEX, CONTEXT, VAR) \
CONTEXT __typeof__(VAR) metamacro_concat(VAR, _weak_) = (VAR);
#define sd_strongify_(INDEX, VAR) \
__strong __typeof__(VAR) VAR = metamacro_concat(VAR, _weak_);
#if DEBUG
#define sd_keywordify autoreleasepool {}
#else
#define sd_keywordify try {} @catch (...) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment