2012-07-19 122 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解釋如何在實際設備上做到這一點