1

Could anyone please tell me am I handling memory correctly in following code in ARC environment? My concern is how would dict object released if I can't use release/autorelease in ARC! I know if it is strong type then it's get released before creating new one but in following look I don't know how would it works.

NSMutableArray *questions = [[NSMutableArray alloc] init];

for (NSDictionary *q in [delegate questions]) 
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:[q objectForKey:@"text"] forKey:@"text"];
    [dict setValue:nil forKey:@"value"];
    [dict setValue:[NSString stringWithFormat:@"%d",tag] forKey:@"tag"];
    [questions addObject:dict];
    dict = nil;
 }
4

1 回答 1

7

是的,您正在dict正确处理您的问题。

如果您有如下代码段:

{
    id __strong foo = [[NSObject alloc] init];
}

当您离开变量的范围时obj,拥有的引用将被释放。对象自动释放。但这并不涉及魔术。ARC 将(在后台)进行如下调用:

{ 
    id __strong foo = [[NSObject alloc] init]; //__strong is the default
    objc_release(foo); 
}

objc_release(...)是一种release调用,但由于它绕过了 objc 消息传递,因此它的性能非常好。

此外,您不需要将变量设置dictnil. ARC 将为您处理此问题。设置对象以nil使对对象的引用消失。当一个对象没有对它的强引用时,该对象被释放(不涉及魔法,编译器将发出正确的调用以使其发生)。要理解这个概念,假设你有两个对象:

{
    id __strong foo1 = [[NSObject alloc] init];
    id __strong foo2 = nil;

    foo2 = foo1; // foo1 and foo2 have strong reference to that object

    foo1 = nil; // a strong reference to that object disappears

    foo2 = nil; // a strong reference to that object disappears

    // the object is released since no one has a reference to it
}

要了解 ARC 的工作原理,我真的建议阅读Mike Ash 博客

希望有帮助。

于 2012-07-11T14:59:52.137 回答