简体   繁体   English

仅在设备文档目录中的第一个可运行文件上创建plist文件

[英]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. 我目前拥有一切设置,可以从documents目录读取并写入该文件,但是由于该文件尚不存在,所以无法执行。

How is a file created within the code? 如何在代码中创建文件?

Use NSFileManger's fileExistsAtPath: to see if the file exist. 使用NSFileManger的fileExistsAtPath:查看文件是否存在。 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];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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