奇怪的重置NSMutableDictionary

时间:2011-07-18 06:54:30

标签: iphone objective-c nsmutabledictionary

我有这个功能:

- (NSMutableDictionary *) getUserDataDictionary
{
    [userDataDicionary removeAllObjects];
    userDataDicionary = [[NSMutableDictionary alloc] initWithContentsOfFile:[self getUserDataDictionaryPath]];

    return userDataDicionary;   
}

- (int) getIndexOfLastVehicle
{
MyAppDelegate *app = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
NSMutableDictionary *tmpUserData = [app getUserDataDictionary];

int lastHighestIndex = -1;

for(id item in [tmpUserData allKeys]){
    NSString *keyInArray = (NSString *)item;

    if ([keyInArray rangeOfString:@"VEHICLE-"].location != NSNotFound) {
        //f.e. "VEHICLE", "1", "TYPE"...or "VEHICLE", "1", "SPZ"...or "VEHICLE", "2", "TYPE" etc
        NSArray * separatedComponents = [keyInArray componentsSeparatedByString:@"-"];
        int indexOfVehicle = [(NSString *)[separatedComponents objectAtIndex:1] intValue];

        if(indexOfVehicle > lastHighestIndex){
            lastHighestIndex = indexOfVehicle;
        }
    }
}

return lastHighestIndex;
}

问题是:
在这段代码之后:

MyAppDelegate *app = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSMutableDictionary *tmpUserData = [app getUserDataDictionary];

int lastVehicleIndex = [self getIndexOfLastVehicle];

tmpUserData是EMPTY。

但是当我改变命令时:

int lastVehicleIndex = [self getIndexOfLastVehicle];

MyAppDelegate *app = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
NSMutableDictionary *tmpUserData = [app getUserDataDictionary];

正确填充tmpUserData。

有人可以解释这种行为吗? 感谢

3 个答案:

答案 0 :(得分:0)

我远远没有成为Objective C中的专业人士,但另一方面我遇到了与az NSMutableArray类似的问题。在我的情况下,问题是某些东西被释放或进入的时间超过了要求。

我建议在这里和那里放几个NSLog()来找出你的内容丢失的地方。我做了这个,我基本上把NSLog放到涉及我的对象的每一条指令上,最后我能够解决这些问题。

只是一个想法,可能会有所帮助。

答案 1 :(得分:0)

此方法存在问题:

- (NSMutableDictionary *) getUserDataDictionary
{
    [userDataDicionary release]; 
    userDataDicionary = [[NSMutableDictionary alloc] initWithContentsOfFile:[self getUserDataDictionaryPath]];

    return userDataDicionary;   
}

答案 2 :(得分:0)

问题之一在于方法getUserDataDictionary。您正在调用removeAllObjects,但不会释放userDataDictionary。您必须释放它而不是removeAllObject。实际版本将为您释放所有对象。