2009-09-17 114 views
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];