Objective-C方法返回NSDictionary而不是NSMutableDictionary。为什么?

时间:2012-08-10 02:27:59

标签: objective-c nsmutablearray objective-c-blocks

我使用included方法返回一个指向NSMutableDictionary的指针,该指针包含在NSArray中。但是,NSMutableArray(theOne)被创建为不可变的NSDictionary。这是一个问题,因为我想在使用此方法检索字典后修改字典。

- (NSMutableDictionary*)getMatFromBoutKey:(NSString*) boutKey
{   
    /*
     * Returns the mat object with the provided boutKey.
     * Returns nil if no mat has that boutKey.
     */

    NSUInteger idx = [[event objectForKey:@"mats"] indexOfObjectPassingTest:
                      ^ BOOL (NSMutableDictionary* obj, NSUInteger idx, BOOL *stop)
                      {
                          return [[obj objectForKey:@"boutKey"] isEqualToString:boutKey];
                      }];

    if (idx == NSNotFound)
        return nil;
    else {
        NSMutableDictionary* theOne = [[event objectForKey:@"mats"] objectAtIndex: idx];
        return theOne;
    }
}

这是在首次引用theOne之后,在断点处停止的调试器的图像。

Image of the debugger showing that theOne is not mutable

为什么不是一个可变的?如何返回指向NSMutableDictionary的指针,以便在我获得返回给我的值后可以修改它?

谢谢!

3 个答案:

答案 0 :(得分:1)

我会假设你有一个数组字典。然后该数组包含一堆常规字典。因此,当您将其从数组中拉出时,无论您将其分配给它,它仍然是常规字典。

例如,请使用以下代码

NSDictionary *dict = [[NSDictionary alloc] init];
NSMutableDictionary *mutDict = dict;

mutDict将包含一个常规字典,因为它没有正确地转换为可变字典。

要么确保在创建[event objectForKey:@" mats"]的数组时将NSMutable词典放在其中,或者

使用

NSMutableDictionary* theOne = [[[event objectForKey:@"mats"] objectAtIndex: idx] mutableCopy];

取出数据时

答案 1 :(得分:1)

一般来说,我认为在不严格需要可变性时使用不可变对象是更好的做法。可变对象使用更多内存,当然也有可能被意外更改。也许在块中被更改为枚举器(我不确定,但它是可能的。为了更快的索引)。如果您想通过 mutableCopy 更改可变对象。或使用其他方法。

答案 2 :(得分:0)

它是否可以在代码中的其他位置插入?如果是这样,它应该返回为可变,如果不是,你可以发送mutableCopy消息来获得一个可变副本(引用计数为1,所以一定要在必要时释放它。)