NSMutableDictionary的奇怪行为

时间:2011-11-11 19:11:36

标签: objective-c nsmutabledictionary

看一下这段代码

- (NSMutableDictionary *)getUsersFromServer
{
//here we're getting list of users from the server
NSMutableDictionary * users = [[[NSMutableDictionary alloc] init] autorelease];

userresults = [[NSMutableArray alloc] init];    

//all this will be replaced with users taken from the server. it's needed just for testing
for (int i = 0;i < 19;i++)
{

    int wins    = i ;         float f_wins = (float)wins;
    int losses  = i * 2 ;     float f_losses = (float)losses;
    int withdr  = i * 3 ;     float f_withdr = (float)withdr;
    float win_per = f_wins / ((f_wins + f_losses + f_withdr) / 100.0);

 [userresults setArray:[NSMutableArray arrayWithObjects:[NSNumber numberWithInt:wins],
                                                                                [NSNumber numberWithInt:losses],
                                                                                [NSNumber numberWithInt:withdr],
                                                                                [NSNumber numberWithFloat:win_per],
                                                                                 nil]]; 
[users setObject:userresults forKey:[NSString stringWithFormat:@"user number %i",i]];

}

[userresults release];
return users;
}

在每次循环迭代中,我用数字填充数组并将其设置为NSMutableDictionary中的值。作为每个数组的键,提供格式化的字符串,它是迭代计数器的唯一数量。所以......问题是 - 字典总是用不同键的SAME数组填充。字典中有19个数组,所有它们都是最后的!那是从最后一次迭代开始的。每个人都有不同的钥匙!!!怎么会发生???这是怎么回事???

2 个答案:

答案 0 :(得分:3)

userresults指向同一个对象,并且您使用setArray:方法修改同一个数组。在每个循环迭代中创建一个新数组:

NSArray *userData = [NSArray arrayWithObjects:[NSNumber numberWithInt:wins],
                                              [NSNumber numberWithInt:losses],
                                              [NSNumber numberWithInt:withdr],
                                              [NSNumber numberWithFloat:win_per],
                                              nil];
[users setObject:userData forKey:[NSString stringWithFormat:@"user number %i",i]];

答案 1 :(得分:0)

用户结果在循环外被不必要地声明。你可以在这里放弃可变数组,并在每次迭代时创建一个新的NSArray。您的问题源于重用循环外声明的数组并每次都放入新值。试试这个:

[users setObject: [NSArray arrayWithObjects:[NSNumber numberWithInt:wins], [NSNumber numberWithInt:losses], [NSNumber numberWithInt:withdr], [NSNumber numberWithFloat:win_per], nil];
[users setObject:userData forKey:[NSString stringWithFormat:@"user number %i",i]]
forKey:[NSString stringWithFormat:@"user number %i",i]];;