1

I finished my App for a distance calculation. I'll update my database before to copy it. I did some tests and when I'm moving my database (DataBase.sqlite) into "Copy Bundle Ressources" and running App on my device, I can't see my data.

Looks like the device is using his own database with same name (DataBase.sqlite). (DataBase will update a TableView during launch)

I created a AddButton to see if I can update my DataBase from an iPhone and it works. I mean is I closed the App an re launched it, I can see the created data from the AddButton.

Have you any idea?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
fred
  • 45
  • 1
  • 7
  • By default, database goes into Document folder. So no need to copy the database. If you are copying then get the path of database's new location and get the data from that location only. – Samkit Jain Aug 13 '13 at 14:22
  • Thanks, I can see iphone's document path -> storeURL NSURL * @"file:///var/mobile/Applications/6718AFE3-00D1-470B-AA4A-E4407E1EB1E3/Documents/DataBase.sqlite" How can I copy the right one ? By changing storeURL ? Sorry or stupid question – fred Aug 13 '13 at 14:38

1 Answers1

0

When you include the database into your bundle via Xcode's "Copy Bundle Resources", it's part of the bundle, i.e. you get the path via:

NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"DataBase" ofType:@"sqlite"];

If you want to copy that to your Documents folder so that you can use it, you get the Documents path via:

NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath   = [documentsFolder stringByAppendingPathComponent:@"DataBase.sqlite"];

So, you might check for existence in Documents, and if not there, copy from bundle to Documents:

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:documentsPath]) {
    NSError *error = nil;
    BOOL success = [fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error];
    NSAssert(success, @"%s: copyItemAtPath failed: %@", __FUNCTION__, error);
}

You can now open the database in the Documents folder (e.g. using documentsPath).

Now, if you ever attempted to open a database in Documents without first copying from the bundle, the standard sqlite3_open will create a blank database. So, you probably want to delete the app from the device/simulator and then reinstall, to get rid of that blank database in Documents (otherwise the above logic, testing for the existence of the database in Documents, will result in false positive).

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • @fred If you started with the standard Core Data template which opens the database in the app delegate, then do it there. See http://stackoverflow.com/a/5633275/1271826 – Rob Aug 13 '13 at 19:02