写plist文件不写

时间:2012-07-19 02:46:40

标签: ios int plist nsdictionary

我想从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.有人可以告诉我我做错了吗?

3 个答案:

答案 0 :(得分: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");
    }
} 

答案 1 :(得分: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. / p>

答案 2 :(得分:0)

我发现这种方法对于实际设备本身并不常见。您需要做的是herethis website说明了如何在实际设备上执行此操作

相关问题