iOS 常用宏定义

/*
    宏定义
    __VA_ARGS__ 表示多个参数部分
    ... 多个不确定的参数
    ## 连接符 左右相连
 */

// 例子 1

#define Zlog(...) NSLog(__VA_ARGS__)

// 例子 2
// 解释 必须添加@是因为autoreleasepool{}存在  __weak_self___
#define weakify( x ) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
autoreleasepool{} __weak __typeof__(x) __weak_##x##__ = x; \
_Pragma("clang diagnostic pop")


#define strongify( x ) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
try{} @finally{} __typeof__(x) x = __weak_##x##__; \
_Pragma("clang diagnostic pop")

// 例子 3
#undef  PERFORM_BLOCK_SAFELY
#define PERFORM_BLOCK_SAFELY( b, ... ) if ( (b) ) { (b)(__VA_ARGS__); }

// 例子 4
#undef  dispatch_main_sync_safe
#define dispatch_main_sync_safe(block) if ([NSThread isMainThread]) { block(); \
} else { dispatch_sync(dispatch_get_main_queue(), block); }

#undef  dispatch_main_async_safe
#define dispatch_main_async_safe(block) if ([NSThread isMainThread]) { block(); \
} else { dispatch_async(dispatch_get_main_queue(), block); }

// 例子 5 单例实现
#undef    singleton
#define singleton( __class ) \
property (nonatomic, readonly) __class * sharedInstance; \
- (__class *)sharedInstance; \
+ (__class *)sharedInstance;

//
#undef    def_singleton
#define def_singleton( __class ) \
dynamic sharedInstance; \
- (__class *)sharedInstance \
{ \
return [__class sharedInstance]; \
} \
+ (__class *)sharedInstance \
{ \
static dispatch_once_t once; \
static __strong id __singleton__ = nil; \
dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \
return __singleton__; \
}

猜你喜欢

转载自www.cnblogs.com/chaochaobuhuifei55/p/9100652.html