【问题标题】:Why does Xcode complain sometimes and not always when self is used inside a block?为什么在块内使用 self 时 Xcode 有时会抱怨而不总是抱怨?
【发布时间】:2016-10-30 09:05:48
【问题描述】:

假设如下情况:

  self.collectionViewController.didEndDisplayingCell = ^(CollectionViewCell *cell) {
    [self doSomething];    
  };

Xcode 会抱怨我不能在该方法中使用 self ,否则我将有一个保留周期。

然后是另一种情况。我创建了一个类,它加载图像并在完成时运行某些东西并调用它

[[MyImageClass sharedInstance] loadImageFromUrl:url
                             runOnCompletion:^(UIImage *image) {
                               [self doSomething];
                             }];

Xcode 在这种情况下不会报错,并且 self 在块内使用!

为什么?

【问题讨论】:

    标签: ios iphone memory-leaks objective-c-blocks


    【解决方案1】:

    第一种情况:

    self 对象保持对块对象的强引用。

    反之亦然,块也保留self 对象。 Since blocks capture their context, package it up, and carry it along for the ride, any reference to self (or implicit reference with an ivar) within a block also will capture a strong reference to self。你可以参考这个https://blackpixel.com/writing/2014/03/capturing-myself.html

    所以,这将是保留周期!

    【讨论】:

    • 那没有解释第二种情况。我的意思是为什么 xcode 没有抱怨。
    • 确保您了解第一种情况。你会理解第二种情况。关于第二种情况:MyImageClasssharedInstance保留块对象,块对象保留self对象,self对象不保持对块对象的强引用。在这种情况下没有保留周期!
    猜你喜欢
    • 2017-01-17
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多