ARC弱局部变量的生命周期 [英] Lifetime of weak local variables with ARC

查看:88
本文介绍了ARC弱局部变量的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一段看起来像这样的代码:

If I have a piece of code that looks like this:

- (void)testSomething
{
  __weak NSString *str = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];
  NSLog(@"%@", str);
}

输出将为(null),因为没有对str的强引用,并且在我分配它后将立即释放它.这是有道理的,并在《过渡到ARC》指南中进行了详细说明.

the output will be (null) because there are no strong references to str and it will be immediately released after I allocate it. This makes sense and is spelled out in the Transitioning to ARC guide.

如果我的代码如下:

- (void)testSomething
{
  __weak NSString *str = [NSString stringWithFormat:@"%@", [NSDate date]];
  NSLog(@"%@", str);
}

然后正确打印出当前日期.显然,您希望它在非ARC环境中工作,因为str将自动释放,因此在此方法退出之前一直有效.但是,在启用ARC的代码中,人们通常认为这两种形式(stringWithFormat& alloc/initWithFormat)是等效的.

then it correctly prints out the current date. Obviously you would expect it to work in a non-ARC world, since str would be autoreleased and therefore valid until this method exits. However, in ARC-enabled code people generally consider the two forms (stringWithFormat & alloc/initWithFormat) to be equivalent.

所以我的问题是,是否可以保证像第二个示例那样的代码在ARC下工作.也就是说,如果我通过通常认为是自动释放的便利构造函数得到的对象的引用很弱,那么是否可以保证在正常范围内安全地使用该引用,这是保证吗?有没有ARC(即直到方法退出)?

So my question is whether code like the second example is guaranteed to work under ARC. That is, if I have a weak reference to an object that I get via what we would normally consider an autoreleasing convenience constructor, is it guaranteed to be safe to use that reference in the same scope I normally would have without ARC (i.e. until the method exits)?

推荐答案

自动释放和分配的约定在ARC世界中仍然适用.唯一的区别是ARC将插入额外的保留/释放调用,以使泄漏对象或访问已分配的对象变得更加困难.

The conventions of autoreleasing and allocing still apply in the world of ARC. The only difference is that ARC will insert extra retain/release calls to make it much harder to leak objects or access a dealloced object.

在此代码中:

__weak NSString *str = [[NSString alloc] initWithFormat:@"%@", [NSDate date]];

保留对象(或等效对象)的唯一位置是分配. ARC将自动插入一个释放命令,从而立即将其释放.

The only place the object is retained (or equivalent) is the alloc. ARC will automatically insert a release command, causing it to be immediately dealloced.

同时,在这段代码中:

 __weak NSString *str = [NSString stringWithFormat:@"%@", [NSDate date]];

按照惯例,便利构造函数(如 )的返回值必须是自动发布的对象*.这意味着当前的自动释放池已经保留了该对象,并且直到池耗尽后才释放它.因此,您几乎可以保证,该对象至少在您的方法持续时间内会存在-尽管您可能不应该依赖此行为.

By convention, the return value of a convenience constructor like this must be an autoreleased object*. That means the current autoreleasepool has retained the object and will not release it until the pool is drained. You are therefore all but guaranteed that this object will exist for at least the duration of your method - although you probably shouldn't rely on this behaviour.

(*或以其他方式保留)

(* or retained in some other way)

这篇关于ARC弱局部变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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