【问题标题】:Objective-C @strongify returns if self is nil如果 self 为 nil,Objective-C @strongify 返回
【发布时间】:2016-02-17 13:31:12
【问题描述】:

我使用弱化/强化宏,我想将下一个逻辑移至宏。

@weakify(self);
BOOL (^matchesFooOrBar)(id) = ^ BOOL (id obj){
    @strongify(self);
    if (self == nil) return; // I want to move it to the macros

strongify 定义:

#define strongify(...) \
    rac_keywordify \
    _Pragma("clang diagnostic push") \
    _Pragma("clang diagnostic ignored \"-Wshadow\"") \
    metamacro_foreach(rac_strongify_,, __VA_ARGS__) \
    _Pragma("clang diagnostic pop")

有什么建议吗?

【问题讨论】:

    标签: objective-c macros reactive-cocoa


    【解决方案1】:

    我花了一些时间弄清楚...

    #define myStrongify(first, ...) \
    _Pragma("clang diagnostic push") \
    _Pragma("clang diagnostic ignored \"-Wshadow\"") \
    metamacro_foreach(rac_strongify_,, __VA_ARGS__) \
    if (!first) { NS_VALUERETURN(NO, BOOL); } \
    _Pragma("clang diagnostic pop")
    

    用法如下:

    BOOL (^matchesFooOrBar)(id) = ^BOOL(id obj) {
        NSLog(@"before");
        myStrongify(obj);
        NSLog(@"after");
    
        // your custom logic here
        ...
    
        return YES;
    };
    

    仅供参考,NS_VALUERETURN 来自苹果文档。请随意测试。

    【讨论】:

    • 向 strongify 添加第二个参数可能是个好主意,它是 null 的默认返回值。
    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多