2012-07-19 124 views
1

我想从plist文件中检索一个整数,递增它,并将其写回plist文件。 “Levels.plist”文件内部是一行,其中包含键LevelNumber,值为1。 我使用此代码检索值:写入plist文件不写

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的控制台输出谁能告诉我什么,我做错了什么?

+0

我假设“'lvl'”也返回0 ...或者,如果你做''NSNumber * lvlNumber = [plistDict objectForKey:@“LevelNumber”];'“,是一个有效的对象还是为空? “'plistDict'”实际上是否加载了信息?如果你“NSLog”“它,你看到它的条目? – 2012-07-19 02:50:45

+0

我在实现的顶部声明'lvl'是一个整数。并以此为plistDict的的NSLog打印出'[plistDict objectForKey:@“LevelNumber”]的intValue]' – Jeeter 2012-07-19 02:52:18

回答

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:调用返回零,除非你实际上已经将文件命名为“Levels.plist.plist”。

请记住,如果该方法碰巧返回nil,则其余代码仍可继续。给定一个nil文件路径,该NSMutableDictionary将返回nil,而后续调用得到的对象了字典也将返回nil,因此您的通话记录显示为0

+0

所以'pathForResource'只需要文件名,而不是扩展? – Jeeter 2012-07-19 16:29:56

+0

工作。谢谢你! – Jeeter 2012-07-19 16:47:39

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"); 
    } 
} 
0

输出什么我发现是,这种方法对于实际设备本身而言不是常规的。你需要做的是描述herethis website解释如何在实际设备上做到这一点