views:

245

answers:

1

I keep getting an error "SQLite Step Failed: attempt to write a readonly database" when using this code to copy a database:

-(void)createEditableCopyOfDatabaseIfNeeded 
{
    // Testing for existence
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                           NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath =
            [documentsDirectory stringByAppendingPathComponent:@"Money.sqlite"];

    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;

    // The writable database does not exist, so copy the default to
    // the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
            stringByAppendingPathComponent:@"Money.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath
                           toPath:writableDBPath
                           error:&error];
    if(!success)
    {
        NSAssert1(0,@"Failed to create writable database file with Message : '%@'.",
                 [error localizedDescription]);
    }
}

I am using the above code in AppDelegate and this:

NSString *writableDBPath =
        [[NSBundle mainBundle] pathForResource:@"Money"
                               ofType:@"sqlite"];

In ViewController.m

I am using http://th30z.netsons.org/2008/11/objective-c-sqlite-wrapper/ what am I doing wrong?

This is happening again and again... It was working fine before but again the problem started.

+1  A: 

The problem is that you cannot write anything to your bundle. To be able to change your database you need to copy it to application's documents or caches folder and work with that copy.

Vladimir
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Money.sqlite"];Then when I use the above code .. It says table not found !
Worked .. after I copied the database again