2012-08-10 43 views
0

我從plist文件中保存/檢索數據,但是我遇到了問題,如果它不存在,我無法創建plist文件。我需要它在應用程序的「文檔」文件夾中創建。 我的代碼是在Xcode中創建plist文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"playersnames.plist"]; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

if (![fileManager fileExistsAtPath: path]) 
{ 
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"playersnames.plist"] ]; 

} 

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; 


NSFileManager *fileManager2 = [NSFileManager defaultManager]; 
//NSMutableDictionary *data; 

if ([fileManager2 fileExistsAtPath: path]) 
{ 
    data = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; 

} 
else 
{ 
    // If the file doesn’t exist, create an empty dictionary 
    data = [[NSMutableDictionary alloc] init]; 

} 

我搜索到解決問題,但沒有機會,我不知道是什麼在代碼中失蹤。

如果有人能向我解釋如何去做。

我的代碼在viewDidLoad中。

在此先感謝。

回答

0

你永遠創建文件 - 改變這個第一參考FILEEXISTS:

if (![fileManager fileExistsAtPath: path]) 
{ 
    path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"playersnames.plist"] ]; 

} 

這樣:

if (![fileManager fileExistsAtPath: path]) 
{ 
    BOOL ret = [[NSDictionary dictionary] writeToFile:path atomically:YES]; 
    assert(ret); // better work! 
} 

你現在應該已經創建的文件。稍後,您將需要通過稍後保存完整字典到同一文件來做同樣的事情。重要提示:測試這些電話的返回碼!

+0

謝謝,對我很好:) – aLFaRSi 2012-08-10 01:19:17