Search code examples
objective-cxcodesqlitefmdb

Saving to database using FMDB crashes on interpreting NSInteger


When the below function is called, I get the EXC_BAD_ACCESS crash. It looks like FMDB is having a problem interpreting the subject_id NSInteger as it makes it through the two NStrings and bombs when it hits this subject_id column in the WHERE clause.

- (void) saveAllData {

if(isDirty) {

    DrillDownAppAppDelegate *appDelegate = (DrillDownAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    FMDatabase *database = [FMDatabase databaseWithPath:appDelegate.getDBPath];    

    if ([database open]) {

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

        [database close];
    }

    isDirty = NO;
}

//Reclaim all memory here.
[title release];
title = nil;
[category_title release];
category_title = nil;

}

The problem is the same as I ran into in another post on FMDB insert problems and this boils down to something wrong with my subject_id member. I believe I am using a wrong declaration in the header. Here it is:

//
//  Subject.h
//  DrillDownApp

    #import <UIKit/UIKit.h>

    @interface Subject : NSObject {
        NSInteger subject_id;
        NSString *category_title;
        NSString *title;
    //    NSMutableArray *quotes;
        BOOL isDirty;
        //  BOOL isDetailViewHydrated;

    }

- (id) initWithPrimaryKey:(NSInteger)pk;
    @property (nonatomic, readwrite) BOOL isDirty;
    //@property (nonatomic, readwrite) BOOL isDetailViewHydrated;
- (void) addSubject;
- (NSInteger)getNextSubjectId;

    @property (nonatomic, assign) NSInteger subject_id;
    @property (nonatomic, copy) NSString * title;
    @property (nonatomic, copy) NSString * category_title;
    //@property (nonatomic, retain) NSMutableArray *quotes;
    //- (void) saveAllData;


    @end

(Note: I edited this majorly as I figured out the rest of it.)


Solution

  • Ok I solved it. FMDB will not work using Integers. You must convert them into Numbers. I found this done in the examples on FMDB doc and there is never an int being passed through an executeUpdate statement.

    So in my example above the way I fixed this was with the following:

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

    I wished this was better documented, but oh well.