簡體   English   中英

(iOS)從Documents文件夾中讀取一個plist - 我得到了正確的路徑但無法加載字典

[英](iOS) Reading a plist from Documents folder - I get correct path but can't load dictionary

我知道在這個問題上已經有很多線程,但我似乎無法找到解決我問題的線程。 我有一個以詞典為根的plist,包含三個數組。 我寫入plist的代碼在模擬器中工作正常,但在設備上是(null)。

  • 我不是要寫入應用程序包,
  • 我的文件路徑是正確的,我在啟動時檢查以確保文件存在於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)在設備上,而不是在模擬器上呢? 如果我在另一篇關於plists的文章中錯過了解決方案,我很抱歉。

編寫代碼時假定文件已存在於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!");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM