ios - 在 block 中强烈捕获属性,正在将应用程序非弧形转换为弧形

标签 ios objective-c uiimageview objective-c-blocks

<分区>

我已将变量声明为 UIViewExtention 的子类。 正在将项目非弧形转换为弧形

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

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

Assigning retained object to weak variable;object will be released after assignment.

我把属性改成了strong..

@property (nonatomic,strong)  UIImageView *sectionPortraitImageView;

然后显示错误是:

Capture strongly in this block is likely to lead to a retain cycle.

如何避免这个错误?

最佳答案

请参阅this Apple documentation关于如何避免在 block 中强烈捕获“ self ”。这是关键部分:

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

如果您需要在您的 block 中访问 ivars,您将需要以下附加模式

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

你可能认为你可以使用 weakSelf->myIvar 但这会导致另一个关于竞争条件的警告。上面的代码还将确保 self 在您的 block 运行时保持事件状态,即使您没有访问 ivars,这也可能是可取的。

最后,如果您的代码使之成为可能,您可能会考虑根本不捕获 self,只捕获您需要的东西,这样可以避免很多这种复杂性:

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

关于ios - 在 block 中强烈捕获属性,正在将应用程序非弧形转换为弧形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27499022/

相关文章:

ios - swift: UIPageViewController 大小

iOS音调生成

c++ - 链接静态 C++ 库时 Objective-C 中的损坏符号表

ios - UIButton的ImageView的tintColor没有改变

ios - 设置和删除UIButton文本标签

iphone - 当子类化以检测其背后的对象时,在透明 UIView 上使用时手势不起作用

ios - UITableView 中的 UITextView 在模拟器上运行时消失

ios - UITextField 背景图片在 iOS 中不起作用

iOS:通过按 UIButton 更改 UIImageView

swift - 如何编程更改使用 Interface Builder 创建的 UIImageView 中图像的高度/宽度?