iOS:ARC环境中的对象发布

app*_*eak 0 objective-c automatic-ref-counting ios5.1

任何人都可以告诉我,我是否在ARC环境中的以下代码中正确处理内存?我担心如果我不能在ARC中使用发布/自动释放,dict对象将如何释放!我知道如果它是强类型然后它会在创建新类型之前被释放但是在下面看起来我不知道它会如何工作.

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;
 }
Run Code Online (Sandbox Code Playgroud)

Lor*_*o B 6

是的,你dict正确处理你的问题.

如果您有以下代码段:

{
    id __strong foo = [[NSObject alloc] init];
}
Run Code Online (Sandbox Code Playgroud)

当你离开变量的范围时obj,拥有的引用将被释放.对象自动释放.但这并不是神奇的东西.ARC会在(引擎盖下)进行如下调用:

{ 
    id __strong foo = [[NSObject alloc] init]; //__strong is the default
    objc_release(foo); 
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

要了解ARC如何工作,我真的建议阅读Mike Ash博客.

希望有所帮助.