1

我想从 plist 文件中检索一个整数,将其递增,然后将其写回 plist 文件。在“Levels.plist”文件中有一行,键LevelNumber为 ,值为1。我使用此代码来检索值:

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels.plist" ofType:@"plist"];;
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
    NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);

当我运行它时,我得到控制台输出 0。有人能告诉我我做错了什么吗?

4

3 回答 3

2

听起来您需要在此过程中进行大量错误检查。

也许是这样的:

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Levels" ofType:@"plist"];
if(filePath)
{
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    if(plistDict)
    {
        NSNumber * lvlNumber = [plistDict objectForKey:@"LevelNumber"];
        if(lvlNumber)
        {
            NSInteger lvl = [lvlNumber integerValue];

            NSLog( @"current lvl is %d", lvl );

            // increment the found lvl by one
            lvl++;

            // and update the mutable dictionary
            [plistDict setObject: [NSNumber numberWithInteger: lvl] forKey: @"LevelNumber"];

            // then attempt to write out the updated dictionary
            BOOL success = [plistDict writeToFile: filePath atomically: YES];
            if( success == NO)
            {
                NSLog( @"did not write out updated plistDict" );
            }
        } else {
            NSLog( @"no LevelNumber object in the dictionary" );
        }
    } else {
        NSLog( @"plistDict is NULL");
    }
} 
于 2012-07-19T02:59:23.507 回答
1
NSString *filePath = [[NSBundle mainBundle] 
          pathForResource:@"Levels.plist" ofType:@"plist"];

NSMutableDictionary* plistDict = [[NSMutableDictionary alloc]
                          initWithContentsOfFile:filePath];
lvl = [[plistDict objectForKey:@"LevelNumber"]intValue];
NSLog(@"%i", [[plistDict objectForKey:@"LevelNumber"]intValue]);

我的猜测是 NSBundle 会为pathForResource:ofType:调用返回 nil,除非您实际上已将文件命名为“Levels.plist.plist”。

请记住,如果该方法恰好返回nil,您的其余代码仍然可以继续。给定一个nil文件路径,NSMutableDictionary将返回 nil,随后从字典中获取对象的调用也将返回nil,因此您的日志调用显示输出为 0。

于 2012-07-19T03:13:53.610 回答
0

我发现这种方法对于实际设备本身并不传统。此处描述了您需要做的事情,并且该网站说明了如何在实际设备上执行此操作

于 2012-07-24T19:25:04.627 回答