Search code examples
databasexcodesqlitefmdb

Why inserting an Integer into SQLite would bomb out?


I get an EXC_BAD_ACCESS on the below insert statement using FMDB executeUpdate. It occurs on the bindObject toColumn in FMDatabase.

In the NSlog statement, I get the correct values, but the update statement bombs out. Not sure what I am doing wrong here.

- (void) addSubject {

    DrillDownAppAppDelegate *appDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate];

    FMDatabase *database = [FMDatabase databaseWithPath:appDelegate.getDBPath];    
    [database open];

    NSLog(@"SUBJECT_ID/TITLE/CATEGORY_TITLE = %d / %@ / %@", self.subject_id, self.title, self.category_title);

    [database executeUpdate:@"insert into SUBJECT (subject_id, subject, category) values(?, ?, ?)", 
    self.subject_id, self.title, self.category_title, nil];

    [database close];

}

I went through the FMDatabase code and it looks like the first variable, subject_id is the one that is bombing out. I tried both saving as an NSInteger as well as NSNumber and both gave same crash.

The exact line from FMDatabase where it crashes is:

    else if ([obj isKindOfClass:[NSData class]]) {

and it is passing the subject_id as an NSInteger (or a NSNumber) and giving the error.


Solution

  • FMDB executeUpdate statement requires that you use NSNumber and not NSInteger so convert your NSInteger into an NSNumber as part of the executeUpdate statement and it will work. I spent hours searching for this and finally found it.

    Here is an example of how it should look:

    [database executeUpdate:@"update Subject Set subject = ?, category = ? where subject_id = ?", self.title, self.category_title, [NSNumber numberWithInt:self.subject_id]];