开发者

Creating a plist file only on first runnable in the device's documents directory

I current have everything setup to read from the documents directory and write to it , but Cannot do it because the file doesnt exist yet.

How is a fi开发者_高级运维le created within the code?


If you already have a template version of the document in your application's bundle then you should be able to write it to the application's document directory using something similar to the following. I haven't tested this code so I've probably got a few things wrong but that's the general idea.

- (void) applicationDidFinishLaunching {
  NSArray* directories = NSSearchPathsForDirectoriesInDomain(NSDocumentsDirectory, NSUserDomainMask, YES);
  NSString* documentsDirectory = [directories objectAtIndex: 0];
  NSString* path = [documentsDirectory stringByAppendingPathComponent: @"Something.plist"];

  if (![[NSFileManager sharedInstance] fileExistsAtPath: path]) {
    NSString* infoTemplatePath = [[NSBundle mainBundle] pathForResource: @"Something" ofType: @"plist"];
    NSDictionary* info = [NSDictionary dictionaryWithContentsOfFile: infoTemplatePath];
    [info writeToFile: path];
  }
}


Use NSFileManger's fileExistsAtPath: to see if the file exist. If not create it before going on to the code that requires the file.


This one works better for me:

        NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentDBFolderPath = [documentsDirectory stringByAppendingPathComponent:@"*.db"];

    if (![fileManager fileExistsAtPath:documentDBFolderPath])
    {
        NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"*.db"];
        [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜