I'm trying to build a class for handling all sqlite3 work and I've encountered an EXC_BAD_ACCESS which I just can't explain. I am new to Objective-C development and memory management in general so I apologize if this is a stupid question.
When initializing the class I get the path to the database file and keep it around:
NSArray * documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
databasePath = [[[documentPaths objectAtIndex:0] stringByAppendingPathComponent:@"Database.sql"] retain];
Then I try to use it and it crashes on me:
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { // crashes
The odd thing is that the exact same line in a different function works perfectly. I tried adding the variable initialization to above the line, but to no avail:
NSArray * documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
databasePath = [[[documentPaths objectAtIndex:0] stringByAppendingPathComponent:@"Database.sql"] retain];
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { // crashes
In both cases the retain count is 2.
However, putting any form of static text in there works fine:
databasePath = @"I have a balloon";
if (sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { // fine
// or
if (sqlite3_open([@"APPLES!" UTF8String], &database) == SQLITE_OK) { // fine
A little more experimentation revealed that it was the UTF8String function that was crashing, but I don't understand why.
Edit: Even more experimentation resulted in me being able to call the UTF8String function but not even use the results:
const char * test = [databasePath UTF8String];
NSLog(@"%@", [NSString stringWithUTF8String:test]); // fine
if (sqlite3_open(test, &database) == SQLITE_OK) { // fails
Edit: Messed around even more and discovered that the problem was in a parameter that I was passing to the function. I had breakpoints all over the place so I was 100% sure that the point it fails is at the line I specified, a line which doesn't use the passed variable, but somehow it caused everything to fail. Sometimes. I have no idea how it went wrong, but I rewrote the entire thing, changed my function call and now it works.
Thanks to all who answered.