views:

49

answers:

1

I'd like to split up executing a query. The myprepare function below opens the database connection and runs the sqlite3_prepare_v2 function. Once sqlite3_open is executed within the scope of the myprepare, selectstmt and database have valid addresses assigned to them. However, once I come out of myprepare, their addresses are wiped to 0x0.

sqlite3_stmt *selectstmt = nil;
sqlite3 *database = nil;

[anInstance myprepare:selectstmt theDatabase:database]; //assignments are fine inside here

//here, the above values will be 0x0

Why aren't the values of selectstmt and database retained outside of myprepare?

+6  A: 

selectstmt and database are pointers to objects. If you want a function to affect the value of the pointer (rather than the object it points to), you would have to pass them by reference. In other words, myprepare:theDatabase: would have to be prototyped as:

- (void)myPrepare:(sqlite3_stmt **)selectstmt theDatabase:(sqlite3 **)database;

And you would have to call it like so:

[anInstance myprepare:&selectstmt theDatabase:&database];

That way you are passing a pointer to a pointer, and you can change the value of the pointer by dereferencing the parameter in the method.

Your database wrapper object really ought to be keeping track of the database handle internally, and you should be passing back your values as return values, as it is almost always cleaner than by reference:

MyClass *anInstance = [[MyClass alloc] initAndOpenDatabase];

sqlite3_stmt *selectstmt = [anInstance prepareStatement];

...

[anInstance close];
[anInstance release];
Frank Schmitt