开发者

check if plist exist, if not load from here

I am trying to check whether a plist exists in my doc folder: if yes, load it, if not load from resource folder.

 - (void)viewWillAppear:(BOOL)animated
 {
 //to load downloaded file
 NSArray *docpaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
 NSString *documentsDirectory =开发者_如何学Go [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];

Where did I go wrong? The plist is not loading from resource folder.


I think if you create an instance of NSFileManager you can then use the file exists method

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

exists = [fileManager fileExistsAtPath:docPath];

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


You need to check wether the file exists in your Documents folder (with NSFileManager or something like this). stringByAppendingPathComponent: doesn’t care wether the path it returns exists or is valid.


I have used a similar approach in one of the applications and it was working fine for me. Where at the launch of the application, I check for the plist file inside the document directory and if it does not exists there, then it is copied from the resource folder.

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];      

}


Here is the Swift version of Chris's Answer:

if (NSFileManager.defaultManager().fileExistsAtPath(path)) {
    // ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜