自我保留在这个Objective-C块中吗? [英] Is self retained within this Objective-C block?

查看:173
本文介绍了自我保留在这个Objective-C块中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Objective-C中有一个看起来像这样的块时:

When I have a block in Objective-C that looks like this:

self.request = [[ASIHTTPRequest requestWithURL:...

[self.longPollRequest setCompletionBlock:^{
    NSLog(@"%@", self.request.responseString);
}];

它会保留 self 还是明确保留 self.request

will it retain self or explicitly retain self.request?

推荐答案

作为块编程主题说:


在引用计数环境中,当您引用
Objective-C对象时,默认为
阻止,保留
。即使你
只是引用对象的实例变量
也是如此。使用__block存储类型
修饰符标记为
的对象变量不会保留。

In a reference-counted environment, by default when you reference an Objective-C object within a block, it is retained. This is true even if you simply reference an instance variable of the object. Object variables marked with the __block storage type modifier, however, are not retained.

如果在方法的实现中使用块,对象
实例变量的内存管理规则
更微妙:

If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:

如果通过引用访问实例变量,则self为
保留;

If you access an instance variable by reference, self is retained;

如果按
值访问实例变量,则保留变量。

If you access an instance variable by value, the variable is retained.

您在块中引用 self ,因此 self 将被保留。

you reference self in block, so self is retained.

这篇关于自我保留在这个Objective-C块中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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