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