首页 文章

在块中强烈捕获属性,将应用程序非弧转换为弧[重复]

提问于
浏览
1

这个问题在这里已有答案:

我已将变量声明为 UIViewExtention 的子类 . 将项目非弧转换为弧

@interface SectionIconView : UIViewExtention 
@property (nonatomic,weak)  UIImageView *sectionPortraitImageView;
@property (nonatomic,weak)  UIImageView *sectionLandscapeImageView;

我已将该属性声明为弱,然后它在.m文件中显示错误,即

将保留对象分配给弱变量;对象将在赋值后释放 .

我已将属性更改为强...

@property (nonatomic,strong)  UIImageView *sectionPortraitImageView;

然后它显示一个错误是:

在此块中强烈捕获可能会导致保留周期 .

如何避免这个错误?

1 回答

  • 2

    有关如何避免在块中强烈捕获"self",请参阅this Apple documentation . 这是关键部分:

    XYZBlockKeeper * __weak weakSelf = self;
    self.block = ^{
        [weakSelf doSomething];   // capture the weak reference
                                  // to avoid the reference cycle
    }
    

    如果您需要访问块中的ivars,则需要以下附加模式

    self.block = ^{
        XYZBlockKeeper * strongSelf = weakSelf;
        // can now access strongSelf->myIvar safely
    }
    

    您可能认为可以使用weakSelf-> myIvar,但这将导致另一个关于竞争条件的警告 . 上面的代码还将确保在块运行时self保持活动状态,即使您不访问ivars也可能需要这样做 .

    最后,如果您的代码使其成为可能,您可能会考虑不捕获自己,只捕获您需要的东西,这避免了很多这种复杂性:

    MyClass *myThing = self.myThing;
    self.block = ^{
        // use myThing here, self is not captured
    }
    

相关问题