Hi, I have a trouble in my database - somehow at some point it appears that a database is being closed even before it was opened.
If a database was not opened I am using the following statement: if (!database) then break;
when *database is being set to nil (database = nil) when it was not opened.
Am I doing it in a right way? Or there is some other error in my code?
Here is my code:
-(BOOL) loadDB: (NSString*) dbPath {
//Database was opened before
if (database) {
sqlite3_close(database);
database = nil;
}
//Opening database
if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK)
{
database = nil;
return FALSE;
}
return TRUE;
}
The code is being called for multiple times and at some time it throws an exception. Why may this happen?
When I am using debugger to see where a problem occured, it shows me: sqlite3_close(database);
Thank you in advance.
-
Your close brace is too early (but I don't think that's the problem because it wouldn't compile.
As a style note, please only return ONE time from a function (and make that at the bottom). Create a BOOL, initialize it to TRUE and change it's value to FALSE when necessary.
Abizern : Multiple returns are useful in certain conditions, so I wouldn't take that as a rule, personally.KevinDTimm : multiple returns mean your function is too large - finding multiple returns isn't just a smell, it's a maintenance stench.Ilya : I redesigned my code according to your recommendation but this didn't help.Ilya : When I am using debugger to see where a problem occured, it shows me: sqlite3_close(database);Abizern : @kevindtimm in this example, multiple returns are stinky and my answer below shows a different way of doing it. But, two returns are common in code where it is a guard condition. e.g. http://stackoverflow.com/questions/710568/some-beginner-objective-c-iphone-questions/710986#710986KevinDTimm : @Abizem - that's probably the only case where I would 'agree' with multiple (only two) returns. I would agree with the indentation assumption, that certainly does hold some credence. -
Try setting the database pointer to NULL instead of nil.
-(BOOL) loadDB: (NSString*) dbPath { BOOL retVal = TRUE //Database was opened before if (database) { sqlite3_close(database); database = NULL; // <-- NULL not nil } //Opening database if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) { database = NULL; // <-- NULL not nil retVal = FALSE; } return retVal; }In Objective C nil is a nil pointer on an object. But
databaseis a pointer to a struct, so use NULL instead.KevinDTimm : too bad he doesn't care to know the answer (or has solved it and not posted the resolution).Abizern : He accepted my answer on the duplicate http://stackoverflow.com/questions/720603/sqlite3close-throws-an-exception/720739#720739
0 comments:
Post a Comment