1

我有一個非常簡單的問題。雖然我對Objective-C相當陌生,但我對語言和內存管理模型非常滿意。收藏集和Objective-C內存管理

我明白所有權和顯式和隱式的概念。我也明白,當你向集合中添加任何東西時,它將獲得關鍵和值的所有權,並釋放版本上的所有權。

我的問題涉及發佈一系列收藏品(又名Bag)。我有以下代碼:


    // levelDict is a member NSMutableDictionary on the Class 

    BOOL newDict = NO; 
    BOOL newArray = NO; 

    NSNumber *levelKey = [NSNumber numberWithInt:toLevel]; 
    NSMutableDictionary *dict = [levelDict objectForKey:levelKey]; 
    if (dict == nil) { 
     dict = [[NSMutableDictionary alloc] init]; 
     [levelDict setObject:dict forKey:levelKey]; 
     newDict = YES; 
    } 

    // Now look for the array... 
    NSNumber *typeKey = [NSNumber numberWithInt:objectType]; 
    NSMutableArray *array = [dict objectForKey:typeKey]; 
    if (array == nil) { 
     array = [[NSMutableArray alloc] init]; 
     [dict setObject:array forKey:typeKey]; 
     newArray = YES; 
    } 

    // Now add the object to the array... 
    [array addObject:object]; 

    // Deal with our memory management 
    if (newArray) { 
     [array release]; 
    } 

    if (newDict) { 
     [dict release]; 
    } 

此代碼創建一個地圖,其中每個條目則包含數組(又名袋)。如果我釋放字典對象levelDict,它擁有每個條目的對象數組,我假設該版本也將級聯到數組中?或者我必須迭代字典並顯式釋放每個數組?

現在爲額外的信用問題 - 爲什麼我這樣做與定義一個集合對象?那麼,在Java等其他語言中,Object實例化可能會非常昂貴。我假設Objective-C就是這種情況。關聯數組的地圖非常高效。

感謝 布萊恩

回答

3

當字典被釋放,所有鍵和值被釋放。如果它們是數組,則釋放它們也將釋放數組中的所有條目,依此類推。

當然,向字典添加任何內容都會保留鍵和值,並且向可變數組添加任何內容都會保留條目。

很簡單...

+0

謝謝!我很確定是這種情況,但希望得到確認。 – user129874 2009-09-17 17:24:10

0

只要NSDictionary是保留給定的NSObjectNSArray包括)的參考的唯一容器,它會得到解除了分配的時候NSDictionary一樣。

0

由於分支不影響保留計數,因此使用autoreleased字典/數組的代碼更簡單。

// levelDict is a member NSMutableDictionary on the Class 

NSNumber *levelKey = [NSNumber numberWithInt:toLevel]; 
NSMutableDictionary *dict = [levelDict objectForKey:levelKey]; 
if (dict == nil) { 
    dict = [NSMutableDictionary dictionary]; 
    [levelDict setObject:dict forKey:levelKey]; 
} 

// Now look for the array... 
NSNumber *typeKey = [NSNumber numberWithInt:objectType]; 
NSMutableArray *array = [dict objectForKey:typeKey]; 
if (array == nil) { 
    array = [NSMutableArray array]; 
    [dict setObject:array forKey:typeKey]; 
} 

// Now add the object to the array... 
[array addObject:object];