【发布时间】:2013-05-10 09:15:15
【问题描述】:
基于您cannot 在枚举可变集合时编辑可变集合这一事实,这是我能想出的编辑 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
this 代码也出现上述错误:
for (NSUInteger idx = 0; idx < [_myMutableArray count]; idx++) {
NSMutableDictionary* myMutableDict = _myMutableArray[idx];
[myMutableDict setObject:obj forKey:key];
}
更新 2: 问题的根源是实例化非可变数组和字典。我是全新 obj-c literals 的新手,所以我不知道要创建 NSMutableArray 和 NSDictionary,你必须分别这样做:
[@[..] mutableCopy]
[@{..} mutableCopy]
【问题讨论】:
-
+1 表示它太复杂了
标签: ios objective-c nsmutablearray enumeration nsmutabledictionary