我有一個非常簡單的問題。雖然我對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就是這種情況。關聯數組的地圖非常高效。
感謝 布萊恩
謝謝!我很確定是這種情況,但希望得到確認。 – user129874 2009-09-17 17:24:10