2013-05-09 33 views
3

我知道這個問題上已經有很多線程,但我似乎無法找到解決我的問題的線程。我有一個以詞典爲根的plist,包含三個數組。我的代碼寫入plist在模擬器中工作正常,但在設備上爲(null)。(iOS)從文檔文件夾讀取plist - 我得到正確的路徑,但無法加載字典

  • 我並不想寫信給應用程序包,
  • 我的文件路徑是正確的,我在發射檢查,以確保文件中的Documents文件夾存在(它確實存在)。

    - (void) writeToPlist:(NSString *)fileName playerColor:(NSString *)player withData:(NSArray *)data 
    { 
        NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES); 
        NSString *documentsDirectory = [sysPaths objectAtIndex:0]; 
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 
    
        NSLog(@"File Path: %@", filePath); 
    
        NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:filePath]; 
    
        NSLog(@"plist: %@", [plistDict description]); 
    
        [plistDict setValue:data forKey:player]; 
    
        BOOL didWriteToFile = [plistDict writeToFile:filePath atomically:YES]; 
        if (didWriteToFile) { 
         NSLog(@"Write to file a SUCCESS!"); 
        } else { 
         NSLog(@"Write to file a FAILURE!"); 
        } 
    } 
    

調試輸出:

File Path: /var/mobile/Applications/CA9D8884-2E92-48A5-AA73-5252873D2571/Documents/CurrentScores.plist 
    plist: (null) 
    Write to file a FAILURE! 

我用同樣的方法在其他項目中,所以我不知道如果我忘了什麼東西或什麼的協議是。我檢查過拼寫/大寫字母並重新制作了plist,沒有任何區別。

那麼,爲什麼plistDict(null)在設備上,而不是在模擬器上?我很抱歉如果我錯過了另一篇文章中的解決方案。

+0

該文件是否存在?這不會是您第一次調用此方法。 – rmaddy 2013-05-09 22:53:43

回答

2

您的代碼被寫入以假定該文件已存在於Documents文件夾中。這種方法第一次被調用時情況並非如此。

您應該添加一個檢查文件的存在。如果它在那裏,請加載它。如果沒有,請在準備寫入數據時進行一些其他適當的數據初始化。

此外,您的字典需要可變,以便您更改或添加鍵/值。

- (void) writeToPlist:(NSString *)fileName playerColor:(NSString *)player withData:(NSArray *)data 
{ 
    NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES); 
    NSString *documentsDirectory = [sysPaths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; 

    NSLog(@"File Path: %@", filePath); 

    NSMutableDictionary *plistDict; // needs to be mutable 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
     plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 
    } else { 
     // Doesn't exist, start with an empty dictionary 
     plistDict = [[NSMutableDictionary alloc] init]; 
    } 

    NSLog(@"plist: %@", [plistDict description]); 

    [plistDict setValue:data forKey:player]; 

    BOOL didWriteToFile = [plistDict writeToFile:filePath atomically:YES]; 
    if (didWriteToFile) { 
     NSLog(@"Write to file a SUCCESS!"); 
    } else { 
     NSLog(@"Write to file a FAILURE!"); 
    } 
} 
+0

如果是這樣的話,他的模擬器版本不能工作嗎? – 2013-05-09 22:57:17

+1

@MarkM通常情況下,文件可能已通過其他方式添加到模擬器中。這就是爲什麼準備將應用程序提交給Apple進行發佈時,必須始終從設備中刪除應用程序並進行乾淨安裝。然後完全測試應用程序以確保應用程序處理乾淨的開始。 – rmaddy 2013-05-09 23:01:01

+0

謝謝,這個伎倆!正如我懷疑的那樣,我忽略了一些簡單的東西。我認爲在應用程序發佈時檢查可寫路徑就足夠了,但我想不是。 – timgcarlson 2013-05-09 23:17:36