2012-07-11 48 views
0

任何人都可以请告诉我,我是否在ARC环境中的以下代码中正确处理内存?我担心的是如果我不能在ARC中使用release/autorelease,将会如何发布dict对象!我知道如果它是强类型,那么它会在创建新类型之前被释放,但在接下来的观察中,我不知道它会如何工作。iOS:ARC环境中的对象发布

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; 
} 

回答

6

是的,您正在正确处理您的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通话,但因为它bypasess objc消息就很表演。

此外,您不需要将变量dict设置为nil。 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 blog的理解。

希望有所帮助。

+1

更好的文档来源是llvm页面:http://clang.llvm.org/docs/AutomaticReferenceCounting.html – mathk 2012-07-11 15:11:34

+0

@mathk +1以供评论。谢谢。 – 2012-07-11 15:17:27

+0

非常感谢你们俩。这非常有用。 – applefreak 2012-07-11 15:25:52