1

基于在枚举可变集合时无法编辑可变集合的事实,这是我可以想出的编辑 NSMutableDictionaries 数组的最佳解决方案:

__block NSMutableDictionary *tempDict = [NSMutableDictionary dictionaryWithCapacity:1];
__block NSUInteger idx;
[_myArray enumerateObjectsUsingBlock:^(NSMutableDictionary* obj, 
                                                        NSUInteger indx, BOOL *stop) {
    if (// some condition is met) {
        tempDict = [obj mutableCopy];
        idx = indx;
    }
}];

[tempDict setObject:[NSNumber numberWithInt:thisQueryResults] forKey:@"resultsNum"];
[_myArray replaceObjectAtIndex:idx withObject:rowSelected];

这似乎太复杂了(即使对于像 obj-c 这样的语言).. 而且由于它涉及两种数据类型(NSMutableArray 和 NSMutableDictionary),我似乎无法将它们干净地归入一个类别.. 建议?

更新:一条评论问我为什么要创建一个可变副本(而不仅仅是一个副本..因为它正在复制一个可变对象)..

假设我只是使用了副本..如果我休息一下,tempDict这就是我得到的:

// tempDict = [obj copy]
po tempDict
$0 = 0x0b28cc10 <__NSArrayI 0xb28cc10>(
1
)

// tempDict = [obj mutableCopy]
po tempDict
$0 = 0x0b28cc10 <__NSArrayM 0xb28cc10>( //notice the M in __NSArrayM as opposed to I above
1
)

在复制的情况下..如果我在后面加上这样的一行: [tempDict setObject:[NSNumber numberWithInt:thisQueryResults] forKey:@"resultsNum"];

我收到此错误:

[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0xb245100

我得到与代码相同的上述错误:

for (NSUInteger idx = 0; idx < [_myMutableArray count]; idx++) {
    NSMutableDictionary* myMutableDict = _myMutableArray[idx];
    [myMutableDict setObject:obj forKey:key];        
}

更新 2: 问题的根源是实例化非可变数组和字典。我是全新的obj-c 文字的新手,所以我不知道要创建 NSMutableArray 和 NSDictionary,你必须分别这样做:

[@[..] mutableCopy]
[@{..} mutableCopy]
4

3 回答 3

1

所以在你的情况下,我不太明白你为什么叫 tempDict = [obj mutableCopy]; 从你写的条件来看,字典已经是可写的了。

你可以使用几个技巧。喜欢使用

for (NSUInteger idx = 0; idx < _myArray.count: idx++_ {
   NSMutableDictionary *obj = _myArray[idx];

  // modify
}

对于 NSDictionaries,您可以获得 allKeys 并遍历该副本。这比使用快速枚举要慢一些,但仍然比使用装箱整数等变通方法来稍后替换要快:)

于 2013-05-10T09:38:02.277 回答
1

In your case you are NOT modifying the array at all only the dictionaries within the array. There are no contstraits on how you modify the objects within the array. Here is a bit of equivalent code:

for (NSMutableDictionary *dict in _myArray) {
    if (someCondition)
         [dict setObject:[NSNumber numberWithInt:thisQueryResults] forKey:@"resultsNum"]
}

You would have a problem if you absolutely needed to replace the object in your array. In that case, if the array is not huge I would suggest the same as @Markus. Iterate over a copy and modify the original.

于 2013-05-10T10:51:30.463 回答
0

也许您可以使用 KVC 并执行以下操作:

NSArray<NSMutableDictionary *> *result = [[_myArray filteredArrayUsingPredicate:[NSPredicate withFormat:@"{YOUR CONDITION}"]] valueForKey:@"mutableCopy"];
于 2016-04-29T23:42:29.490 回答