开发者

iOS: How to copy database to iphone?

My application uses a database and at the beginning I want to check if the database is already copied to the documents directory. If it isn't it is supposed to be copied there.

What might be wrong with the code below? It worked fine for me until this morning... For some reason the database that is created in the documentsDirectory of the iPhone is completely empty.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.databaseName = @"iWorkoutDatabase";
    NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentsPath objectAtIndex:0];
    self.databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
}

- (void)checkAndCreateDatabase{
    BOOL databaseIsSaved;

    NSFileManager *fileManager = [NSFileManager defaultManager];
    databaseIsSaved = [fileManager fileExistsAtPath:databasePath];
    if (database开发者_如何学编程IsSaved == YES) {
        return;
    }
    else {

        NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
        [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    }
    [fileManager release];
}

I'm going crazy trying to figure this out so it would be great if someone could help me... EDIT: I added the relevant code from the viewDidLoad method and I looked at the documents path from the iPhone simulator and a file was actually created there but it was an empty one.


The code should work, I think. However, there are a few things left to improve that might also solve your problems:

  • do not release a shared instance -- in your case don't release the fileManager
  • Use pathForResource:ofType: to get the full path of your file directly, instead of creating the path on your own

  • Where is databasePath coming from? Is is set correctly?

  • Did you check the database file included with your app, maybe it's broken?
  • Did you try to do a clean build?
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜