0
我搜索了周围,并认为我找到了答案,但它似乎并没有工作。我正在尝试制作一个字典的数组以供日后排序等。我可以将所有正确的数据写入字典对象和密钥对,但是当我尝试将字典添加到数组时,以前的数组条目会被“覆盖”。我意识到我在指向NSArray的指针上做错了什么,但我无法弄清楚。有一篇文章建议将数组的实例化移出for循环,但以下两个代码片段会产生相同的结果。NSMutableArray覆盖for循环
NSMutableDictionary *tempMatricesNW = [NSMutableDictionary dictionary];
NSUInteger middle = 0;
if (([factorsNW count] % 2) != 0) {
middle = (([factorsNW count]+1)/2)-1;
}
NSMutableArray *tempMatriceArrayNW = [NSMutableArray array];
for (NSUInteger i = 1; i < [factorsNW count]-1; i++) {
if (i == middle) {
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"x"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"y"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]-[[factorsNW objectAtIndex:i] intValue]] forKey:@"diff"];
[tempMatriceArrayNW addObject:tempMatricesNW];
}
else {
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"x"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:(([factorsNW count]-i)-1)] intValue]] forKey:@"y"];
[tempMatricesNW setObject:[NSNumber numberWithInt:abs([[factorsNW objectAtIndex:i] intValue] - [[factorsNW objectAtIndex:(([factorsNW count]-i)-1)] intValue])] forKey:@"diff"];
[tempMatriceArrayNW addObject:tempMatricesNW];
}
NSLog(@"%@", tempMatriceArrayNW);
}
我得到相同的结果与此...
NSMutableDictionary *tempMatricesNW = [NSMutableDictionary dictionary];
NSUInteger middle = 0;
if (([factorsNW count] % 2) != 0) {
middle = (([factorsNW count]+1)/2)-1;
}
for (NSUInteger i = 1; i < [factorsNW count]-1; i++) {
NSMutableArray *tempMatriceArrayNW = [NSMutableArray array];
if (i == middle) {
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"x"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"y"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]-[[factorsNW objectAtIndex:i] intValue]] forKey:@"diff"];
[tempMatriceArrayNW addObject:tempMatricesNW];
}
else {
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:i] intValue]] forKey:@"x"];
[tempMatricesNW setObject:[NSNumber numberWithInt:[[factorsNW objectAtIndex:(([factorsNW count]-i)-1)] intValue]] forKey:@"y"];
[tempMatricesNW setObject:[NSNumber numberWithInt:abs([[factorsNW objectAtIndex:i] intValue] - [[factorsNW objectAtIndex:(([factorsNW count]-i)-1)] intValue])] forKey:@"diff"];
[tempMatriceArrayNW addObject:tempMatricesNW];
}
NSLog(@"%@", tempMatriceArrayNW);
}
这似乎并不重要,我把NSMutableArray中的实例,所以我必须做一些别的错误...
在此先感谢您的帮助!
实例化一个新的'NSDictionary'在每个循环 – Volker
太棒了!这很有用,非常感谢。它甚至是完美的。 –
@ SonGoku68的答案似乎显示相同的解决方案,你可能会考虑接受它,所以其他用户看到这个问题有一个有用的答案。 – Volker