iOS小菜那些年写过的宏文件

一、对新手有用而不一定知道的几个宏

  这里要吐槽的是,很多人加载了libextobjc的Pod库,却只用到@weakify(self)和@strongify(self),真是浪费的无法理解,自己写一个,或者把要用的扒出来不行吗。。。

  首先,挂出自己写的,现在用的顺手的几个宏,希望能对新手们有所帮助

/* ---------   主线程执行 --------- */
#define excecuteOnMain(a) if ([NSThread isMainThread]) {
                              a
                          }
                          else {
                              dispatch_async(dispatch_get_main_queue(), ^{
                                  a
                              });
                          }

/* ---   weak strong Dance ------ */
#ifdef DEBUG
    #define ext_keywordify autoreleasepool {}
#else
    #define ext_keywordify try {} @catch (...) {}
#endif

#define weakify(self) 
    ext_keywordify 
    __attribute__((objc_ownership(weak))) __typeof__(self) self_weak_ = (self)

#define strongify(self) 
    ext_keywordify 
_Pragma("clang diagnostic push") 
_Pragma("clang diagnostic ignored "-Wshadow"") 
    __attribute__((objc_ownership(strong))) __typeof__(self) self = (self_weak_)
_Pragma("clang diagnostic pop")

/* --------   空语句挂载断点 ------ */
#ifdef DEBUG
    #define __NOP__ assert(1)
#else
    #define __NOP__
#endif

使用示例

- (void)viewDidLoad {
    [super viewDidLoad];
    @weakify(self);
    self.block =^{
        @strongify(self);
        __NOP__;
        self.view.backgroundColor = [UIColor redColor];
    };
    excecuteOnMain(
        self.block();
    )
}

二、那些年写过的宏文件  

  初学iOS时,保留着C程序员的习惯,什么东西,方法也好,常量也好,代码块也好,都喜欢写成宏,而写了几百行的宏定义。截图如下,要用的童鞋可以拿去用。我现在会觉得,有些方法类的宏还是写到util类里比较好呢,会比较好调试呢。编程之路法无定法,看个人喜好了。同时,也缅怀下那些青葱岁月,没有屏幕适配,没有如今要从iOS6.0兼容到9.3的艰辛,一切单纯而美好^ ^

原文地址:https://www.cnblogs.com/hushuai-ios/p/5285895.html