Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

aram063

macrumors newbie
Original poster
Dec 26, 2008
6
0
Hi guys,

I am trying to make a program which inserts values into a sqlite database. For some reason my program crashes every time I press the button to insert the value. I have been trying to fix this for a long time but have not been able to fix it. Can you please have a look at my code and tell me what's wrong. Im going to put the code of my .m files on here.
Im really lost guys...don't know what's wrong!:confused:
BpValue.m
Code:
#import "BpValue.h"

static sqlite3 *database = nil;
static sqlite3_stmt *addStmt = nil;

@implementation BpValue

@synthesize valueID, value, isDirty, isDetailViewHydrated;

+ (void) finalizeStatements {
	
	if(database) sqlite3_close(database);
	if (addStmt) sqlite3_finalize(addStmt);
}

- (id) initWithPrimaryKey:(NSInteger) pk {
	
	[super init];
	valueID = pk;
	
	isDetailViewHydrated = NO;
	
	return self;
}

- (void) addValue {
	
	if(addStmt == nil) {
		const char *sql = "insert into BPressure(Value) Values(?)";
		if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
			NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
	}
	
	sqlite3_bind_double(addStmt, 1, [value doubleValue]);
	
	if(SQLITE_DONE != sqlite3_step(addStmt))
		NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
	else
		//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
		valueID = sqlite3_last_insert_rowid(database);
	
	//Reset the add statement.
	sqlite3_reset(addStmt);
}

- (void) dealloc {
	
	[value release];
	[super dealloc];
}

@end

MyViewController.m

Code:
#import "MyViewController.h"
#import "HelloWorldAppDelegate.h"
#import "sqlite3.h"
#import "BpValue.h"


@implementation MyViewController

@synthesize textField;
@synthesize label;
@synthesize string;



- (IBAction)changeGreeting:(id)sender {
	HelloWorldAppDelegate *appDelegate = (HelloWorldAppDelegate *)[[UIApplication sharedApplication] delegate];
	BpValue *bpObj = [[BpValue alloc] initWithPrimaryKey:0];
	NSDecimalNumber *temp = [[NSDecimalNumber alloc] initWithString:textField.text];
	bpObj.value = temp;
	[temp release];
	self.string = textField.text;
	
    NSString *nameString = string;
    if ([nameString length] == 0) {
        nameString = @"World";
    }
    NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString];
    label.text = greeting;

	//Add the object
	[appDelegate addValue:bpObj];
	
    [greeting release];
	
}



- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    if (theTextField == textField) {
        [textField resignFirstResponder];
    }
    return YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		// Initialization code
	}
	return self;
}



/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */

/*
 If you need to do additional setup after loading the view, override viewDidLoad.
- (void)viewDidLoad {
}
 */


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[super dealloc];
	[label release];
    [string release];
    [super dealloc];
}


@end
HelloWorldAppDelegate.m
Code:
#import "MyViewController.h"
#import "HelloWorldAppDelegate.h"
#import "BpValue.h"


@implementation HelloWorldAppDelegate

@synthesize window;
@synthesize myViewController;
@synthesize valuesArray;


- (void)applicationDidFinishLaunching:(UIApplication *)application {
	
	//Copy database to the user's phone if needed.
	[self copyDatabaseIfNeeded];
	
	NSMutableArray *tempArray = [[NSMutableArray alloc] init];
	self.valuesArray = tempArray;
	[tempArray release];
	
    MyViewController *aViewController = [[MyViewController alloc]
										 initWithNibName:@"ControllerView" bundle:[NSBundle mainBundle]];
    self.myViewController = aViewController;
    [aViewController release];
	
    UIView *controllersView = [myViewController view];
    [window addSubview:controllersView];
    [window makeKeyAndVisible];
}


- (void)applicationWillTerminate:(UIApplication *)application {
	// Save data if appropriate
	
	//Save all the dirty coffee objects and free memory.
	[self.valuesArray makeObjectsPerformSelector:@selector(saveAllData)];
	
	[BpValue finalizeStatements];
}

- (void)dealloc {
	[valuesArray release];
    [myViewController release];
    [window release];
    [super dealloc];
}

- (void) copyDatabaseIfNeeded {
	
	//Using NSFileManager we can perform many file system operations.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	NSString *dbPath = [self getDBPath];
	BOOL success = [fileManager fileExistsAtPath:dbPath];
	
	if(!success) {
		
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Database.sqlite"];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
		
		if (!success)
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
}

- (NSString *) getDBPath {
	
	//Search for standard documents using NSSearchPathForDirectoriesInDomains
	//First Param = Searching the documents directory
	//Second Param = Searching the Users directory and not the System
	//Expand any tildes and identify home directories.
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	return [documentsDir stringByAppendingPathComponent:@"Database.sqlite"];
}

- (void) addValue:(BpValue *)bpObj {
	
	//Add it to the database.
	[bpObj addValue];
	
	//Add it to the coffee array.
	[valuesArray addObject:bpObj];
}

@end

Please if someone knows whats wrong, please tell me. It crashes at sqlite_prepare3. Following is part of the crash report

Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000030
Crashed Thread: 0

Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A345)

Thread 0 Crashed:
0 libsqlite3.0.dylib 0x93d211f0 sqlite3Prepare + 48
1 HelloWorld 0x000031c8 -[BpValue addValue] + 89 (BpValue.m:38)
2 HelloWorld 0x00002b70 -[HelloWorldAppDelegate addValue:] + 36 (HelloWorldAppDelegate.m:84)
3 HelloWorld 0x00002e6b -[MyViewController changeGreeting:] + 509 (MyViewController.m:41)
4 UIKit 0x30a5e25e -[UIApplication sendAction:to:from:forEvent:] + 116
5 UIKit 0x30abb022 -[UIControl sendAction:to:forEvent:] + 67
6 UIKit 0x30abb4ea -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 478
7 UIKit 0x30aba830 -[UIControl touchesEnded:withEvent:] + 483
8 UIKit 0x30a75c0b -[UIWindow sendEvent:] + 454
9 UIKit 0x30a65e07 -[UIApplication sendEvent:] + 269
10 UIKit 0x30a6522a _UIApplicationHandleEvent + 4407
11 GraphicsServices 0x31699522 SendEvent + 35
12 GraphicsServices 0x3169b88c PurpleEventTimerCallBack + 276
13 com.apple.CoreFoundation 0x971be615 CFRunLoopRunSpecific + 3141
14 com.apple.CoreFoundation 0x971becf8 CFRunLoopRunInMode + 88
15 GraphicsServices 0x31699d38 GSEventRunModal + 217
16 GraphicsServices 0x31699dfd GSEventRun + 115
17 UIKit 0x30a5dadb -[UIApplication _run] + 440
18 UIKit 0x30a68ce4 UIApplicationMain + 1258
19 HelloWorld 0x00002650 main + 102 (main.m:14)
20 HelloWorld 0x000025be start + 54

Thread 1:
0 libSystem.B.dylib 0x93b624a6 mach_msg_trap + 10
1 libSystem.B.dylib 0x93b69c9c mach_msg + 72
2 com.apple.CoreFoundation 0x971be0ce CFRunLoopRunSpecific + 1790
3 com.apple.CoreFoundation 0x971becf8 CFRunLoopRunInMode + 88
4 WebCore 0x32a8a450 RunWebThread + 384
5 libSystem.B.dylib 0x93b936f5 _pthread_start + 321
6 libSystem.B.dylib 0x93b935b2 thread_start + 34

Thread 2:
0 libSystem.B.dylib 0x93b624a6 mach_msg_trap + 10
1 libSystem.B.dylib 0x93b69c9c mach_msg + 72
2 GraphicsServices 0x3169ce0a EventReceiveThread + 467
3 libSystem.B.dylib 0x93b936f5 _pthread_start + 321
4 libSystem.B.dylib 0x93b935b2 thread_start + 34

Thread 3:
0 libSystem.B.dylib 0x93b624a6 mach_msg_trap + 10
1 libSystem.B.dylib 0x93b69c9c mach_msg + 72
2 com.apple.CoreFoundation 0x971be0ce CFRunLoopRunSpecific + 1790
3 com.apple.CoreFoundation 0x971becf8 CFRunLoopRunInMode + 88
4 com.apple.CFNetwork 0x95a59a32 CFURLCacheWorkerThread(void*) + 396
5 libSystem.B.dylib 0x93b936f5 _pthread_start + 321
6 libSystem.B.dylib 0x93b935b2 thread_start + 34

Thread 0 crashed with X86 Thread State (32-bit):
eax: 0x000040b0 ebx: 0x0000317d ecx: 0xffffffff edx: 0x00003e18
edi: 0x00000000 esi: 0x004123a0 ebp: 0xbfffe5c8 esp: 0xbfffe470
ss: 0x0000001f efl: 0x00010282 eip: 0x93d211f0 cs: 0x00000017
ds: 0x0000001f es: 0x0000001f fs: 0x00000000 gs: 0x00000037
cr2: 0x00000030
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.