2010-09-06 83 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)) { 
    // ... 
} 
相关问题