2010-09-06 92 views
2

我想檢查我的doc文件夾中是否存在plist:如果是,請加載它,如果不是從資源文件夾加載。檢查plist是否存在,如果沒有從這裏加載

- (void)viewWillAppear:(BOOL)animated 
{ 
//to load downloaded file 
NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [docpaths objectAtIndex:0]; 
NSString *docpath = [documentsDirectory stringByAppendingPathComponent:@"downloadedfile.plist"]; 

//if document folder got file 
    if(docpath != nil) 
    { 
    NSDictionary *dict = [[NSDictionary alloc] 
    initWithContentsOfFile:docpath]; 
    self.allNames = dict; 
    [dict release]; 
    } 
    //on error it will try to read from disk 

    else { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"resourcefile" 
      ofType:@"plist"]; 
    NSDictionary *dict = [[NSDictionary alloc] 
    initWithContentsOfFile:path]; 
    self.allNames = dict; 
    [dict release]; 

    } 
    [table reloadData]; 

我哪裏出錯了? plist未從資源文件夾加載。

回答

2

我認爲,如果你創建的NSFileManager的實例,就可以使用該文件存在方法

BOOL exists; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

exists = [fileManager fileExistsAtPath:docPath]; 

if(exists == NO) 
{ 
// do your thing 
} 
0

您需要請檢查是否在文件中您的文檔文件夾中存在(與NSFileManager或類似這樣的東西)。 stringByAppendingPathComponent:並不在意它返回的路徑是否存在或有效。

0

我在其中一個應用程序中使用了類似的方法,它對我來說工作正常。在應用程序啓動時,我檢查文檔目錄中的plist文件,如果它不存在,則從資源文件夾複製該文件。

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; 

NSString * plistName = @"FlowerList"; 
NSString * finalPath = [basePath stringByAppendingPathComponent: 
         [NSString stringWithFormat: @"%@.plist", plistName]]; 
NSFileManager * fileManager = [NSFileManager defaultManager]; 

if(![fileManager fileExistsAtPath:finalPath]) 
{ 
    NSError *error; 
    NSString * sourcePath = [[NSBundle mainBundle] pathForResource:@"FlowerList" ofType:@"plist"]; 
    [fileManager copyItemAtPath:sourcePath toPath:finalPath error:&error];  

} 
0

這裏是克里斯的答案雨燕版本:

if (NSFileManager.defaultManager().fileExistsAtPath(path)) { 
    // ... 
} 
相關問題