2012-07-11 21 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