【问题标题】:Using typeof(self) in Objective-C blocks to declare a strong reference在 Objective-C 块中使用 typeof(self) 来声明一个强引用
【发布时间】:2014-10-07 22:52:44
【问题描述】:

使用weakSelf/strongSelf 模式来避免在块中创建保留循环,这段代码很常见:

typeof(self) __weak weakSelf = self;
void (^block)() = ^{
    typeof(weakSelf) strongSelf = weakSelf;
    // ...more code...
};

问题是,将第二个typeof(weakSelf) 更改为typeof(self) 是否会导致self 在块中被捕获?

例如:

typeof(self) __weak weakSelf = self;
void (^block)() = ^{
    typeof(self) strongSelf = weakSelf; // does using typeof(self) here end up capturing self?
    // ...more code...
};

如果 self 没有被捕获,是否有任何理由偏爱一种方式或另一种方式?

【问题讨论】:

    标签: objective-c objective-c-blocks


    【解决方案1】:

    不应该。如果是这样,那就是编译器错误。

    typeof 表达式实际上并未引用变量 self 或其值。它严格来说是对表达式类型的引用,而不是它的值。该表达式严格来说是一个编译时构造,不会在编译后的代码中存在。

    就我个人而言,我更喜欢typeof(self),但我不认为有一个强有力的论据可以选择其中一个。

    【讨论】:

    • 不是我不相信你,但如果有证据支持你的想法就好了。
    【解决方案2】:

    它没有。 Ken 所说的 typeof 是一个编译时表达式确实适用。

    还有一段代码可以证明这一点:

    #import <Foundation/Foundation.h>
    
    int main(int argc, char *argv[]) {
      @autoreleasepool {
        NSObject *o = [NSObject new];
    
        __weak typeof(o) weakO = o;
        void(^b)() = ^{
          __strong typeof(o) strongO = weakO;
          NSLog(@"o: %@", strongO);
        };
    
        o = nil;
        b();
        /* outputs:
          2015-05-15 16:52:09.225 Untitled[28092:2051417] o: (null)
         */
      }
    }
    

    【讨论】:

    • 您知道将其转换回强的方法吗?我试过 __strong typeof(weakSelf) strongSelf = weakSelf;它没有用,它被释放了,因为它仍然很弱。我问的原因是我没有使用 self,我需要它作为一个块,但作为一种解决方法,我可以定义完整类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多