ARC,自我和块 [英] ARC, self and blocks

查看:99
本文介绍了ARC,自我和块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我理解在复制的块中使用self是不能

I thought I understood the usage of self in a block that is copied is a no no.

但是为了清理我的代码我在Xcode中启用了一堆警告,一个名为向弱指针发送消息

But in an attempt to clean my code i enabled a bunch of warnings in Xcode, one called "Sending messages to weak pointers"

所以现在在我的所有块中,每次我使用我创建的 weakself 引用 __ weak typeof(self)weakself = self;

so now in all my blocks, every time I use my created weakself reference __weak typeof(self) weakself = self;

我收到此警告:弱接收器可能无法预测地设置为nil

一个简单的例子:

__weak typeof(self) weakself = self;
[aClass doSomethingInABlock:^{

     [weakself doSomething]; //warning.

}];

我已经看到了在块中定义self版本的答案,如下所示:

I have seen answers which define a version of self within the block like so:

__weak typeof(self) weakself = self;
[aClass doSomethingInABlock:^{
     typeof(self) selfref = weakself; 
     [selfref doSomething]; //no warning.

}];

所以我想知道这里到底发生了什么:

So I'm wondering what actually happens here:


  • 我只是在欺骗编译器吗?

  • 对弱引用的强引用有什么作用?

  • 我缺少的任何其他东西。

谢谢。

推荐答案


我以为我理解一个块中self的用法是否定的。

I thought I understood the usage of self in a block is a no no.

这不是严格正确的。块保留其中的对象,因此如果您的块被 self 中使用 self c> 。

This is not strictly correct. Blocks retain the objects in them, so don't use self in a block if your block is retained by self.

例如,您可以在UIView动画块中使用 self 。这是因为您的视图控制器(或任何调用动画的代码)没有指向UIView动画块的指针。)

For example, you can use self just fine in a UIView animation block. This is because your view controller (or whatever code is calling the animation) doesn't have a pointer to the UIView animation block.)


我只是欺骗编译器吗?

Am I just tricking the compiler?

否。


对弱引用的强引用有什么作用?

What does a strong reference to a weak reference do?

如果弱引用不是 nil ,接收器的保留计数增加。这将阻止对象在您使用时被释放。

If the weak reference is not nil, the retain count of the receiver is increased. This will stop the object from being deallocated while you're using it.

请记住,当对象不再有强引用时,ARC将释放对象。通过在块内创建一个强引用,你可以防止可能的释放,直到你完成它。

Remember, ARC will deallocate objects when there are no longer strong references to them. By creating a strong reference inside the block, you're preventing possible deallocation until you're done with it.


我还有别的什么丢失。

anything else I'm missing.

我建议你阅读实际内存管理部分。特别是,请阅读使用弱引用以避免保留周期小节。

I recommend reading the Practical Memory Management section of the Advanced Memory Management Programming Guide. Especially, read the subsection "Use Weak References to Avoid Retain Cycles".

这篇关于ARC,自我和块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆