0

I am trying to create a plist file that I will write to later in my app. In the first viewDidLoad I call the following method

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

    if (![fileManager fileExistsAtPath:documentDBFolderPath])
    {
        NSLog(@"file doesnt exist");
        NSString *resourceDBFolderPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.plist"];
        [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error];
    }
    else{
        NSLog(@"file exists");
    }
}

However every time I run the app, I cannot find a file created, and if I close the app and reopen, NSLog shows that file doesnt exist again. Am I missing something?

JeffN
  • 1,575
  • 15
  • 26

2 Answers2

1

You're ignoring the return value and error from -copyItemAtPath:toPath:error:. I'm willing to bet that call is returning NO and populating some error. You should check the return value of that and print out the error if it returns NO.

One possible reason why this is failing is you might not actually have a Documents folder yet, for some reason. You can ask NSFileManager to create it for you.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • How do I check the return value. I checked the path there is a documents folder, but not document – JeffN Oct 30 '12 at 22:36
  • BOOL success = [fileManager copyItemAtPath:resourceDBFolderPath toPath:documentDBFolderPath error:&error]; if(success){// worked} else{//NSLog(@"ERROR: %@", [error localizedDescription]}; – yeesterbunny Oct 30 '12 at 22:51
  • It wasn't creating the file, therefore the file wouldn't copy. Fixed the problem just having it check to see if the file exists, and if it does not, then it creates the file. – JeffN Oct 31 '12 at 23:08
0

Print your resource path and see if the file exists in there. If so, but not working check this question: Working with paths from [[NSBundle mainBundle] resourcePath]

Anyway, if your resource is in your main bundle you can always use:

- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
Community
  • 1
  • 1
atxe
  • 5,029
  • 2
  • 36
  • 50
  • The document does not exist at the path. Any idea why? – JeffN Oct 30 '12 at 22:39
  • Is it being copied in your bundle? You can check it `Project > Target > Build Phases > Copy Bundle Resources` – atxe Oct 30 '12 at 22:49
  • It wasn't creating the file, therefore the file wouldn't copy. Fixed the problem just having it check to see if the file exists, and if it does not, then it creates the file. – JeffN Oct 31 '12 at 23:09