简体   繁体   中英

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 file created within the code?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM