开发者

Why is NSFileManager not working?

I've written some code to copy a file (dbtemplate.sqlite) from the application package to the library. However, no file shows up in the library and every time I start the application it logs the text that it copied the template. There are no errors showing up in the console. What am I doing wrong?

NSFileManager *fileManager = [开发者_如何学编程NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:@"~/Library/AppSafe/database/db.sqlite"]) {

    [fileManager createDirectoryAtPath:@"~/Library/AppSafe/database" withIntermediateDirectories:YES attributes:nil error:nil];

    [fileManager copyItemAtPath:@"dbtemplate.sqlite" toPath:@"~/Library/AppSafe/database/db.sqlite" error:nil];
    NSLog(@"copied template");

}


If I remember correctly, you have to pass a full path into the NSFileManager methods, and using a tilde-prefixed path won't work.

So instead of using @"~/Library/...", use:

[@"~/Library/..." stringByExpandingTildeInPath]


I believe your problem lies in copyItemAtPath:, since the string you give is not a proper path. Use something like [[NSBundle mainBundle] pathForResourceWithName:] to get the actual path to the resource. Also, I'm not sure that the ~ in your paths is supported - you may need to use some function of NSString to expand it.


I would recommend saving files in the documents folder, im not sure if you can even save files in the library folder. Use this code to create a path to your file in the documents folder:

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];

And simply check if it exists like this:

if (![fileManager fileExistsAtPath:path])

So better move your files to the documents folder.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜