Pheepster
Pheepster

Reputation: 6367

Write access to Sqlite in iOS application

I have an issue writing to a Sqlite DB and an answer to a recent question gave a clue as to why I am unable to update/insert. I am getting a reference to the file from the main bundle and attempting to insert a record. This doesn't work since, as I've discovered, the main bundle is read-only. I need to be able to have read/write access to my Sqlite database. Can someone point me to a simple explanation of executing an insert for Sqlite in an iOS app? Thanks, Viv

Upvotes: 0

Views: 261

Answers (1)

Nils Hott
Nils Hott

Reputation: 1690

You need to create a copy of the db you have in your main bundle to get write access. Like so:

// Path to db
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* path = [paths objectAtIndex:0];
// Name of DB:
NSString* fullPath = [path stringByAppendingString:@"/original.db"];
// FileManager, to open db:
NSFileManager* fm = [NSFileManager defaultManager];
// do we already have a local copy?
if (![fm fileExistsAtPath:fullPath]) {
    NSString* pathForNewDB = [[NSBundle mainBundle] pathForResource:@"database" ofType:@"db"];
    // create local copy:
    [fm copyItemAtPath:pathForNewDB toPath:fullPath error:NULL];
}

Upvotes: 1

Related Questions