views:

37

answers:

3

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?

+1  A: 

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

TechZen
+1  A: 

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];
  }
}
Bryan Kyle
I would like to write to files from other classes. Do I try something similar to the above code in the applicationDidFinishLoading method and then put the same code with their unique paths in the other classes? Also Do I need to have e.g. something.plist as an empty plist in my resources folder? regards
alJaree
+1  A: 

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