I'm think there are some basic misunderstandings of how this should work and I would appreciate any help. I've been trying to write some functions that will pull data from a sqlite table, put it in a object, and save that object into an array. That array will then be accessed by other routines. There is a lot more to this class that I don't want to clog the forum with. The problems I'm having this with are:
1) I can only seem to access the final values that were put into the array. Am I saving the 'User' object incorrectly to the array?
2) Assuming that I get the objects correctly in the array, am I pulling them out correctly? I added a sample pull routine at the bottom.
3) Can anyone with more experience mention a more efficient way of doing this? I'm still trying to get my xcode programming legs under me and would appreciate any suggestions to writing cleaner code.
// **SQLiteFunctions header
#import <sqlite3.h>
#import "Users.h"
@interface SQLiteFunctions : NSObject
{
@public
// initializing public variables
NSMutableArray *returnData;
@private
// initializing private variables
sqlite3 *dbPointer;
sqlite3_stmt *sqlStatement;
NSArray *paths;
NSString *documentsDirectory;
NSString *databasePath;
char *error;
Users *users;
}
// initializing public member functions
-(BOOL)openDatabase: (NSString *) table_name;
-(BOOL)openBundleDatabase;
-(BOOL)openNonBundleDatabase;
-(void)closeDatabase;
-(BOOL)getRecords:(const char *)sqlquery;
-(int)getUserRecords:(const char *)sqlquery;
@end
//**SQLiteFunctions implementation
-(int)getUserRecords:(const char *)sqlquery
{
// retreiving database values
users = [[Users alloc] init];
// initializing return data array
returnData = [[NSMutableArray alloc] init];
// testing prepare statement for verse sql
if(sqlite3_prepare(dbPointer, sqlquery, -1, &sqlStatement, NULL) == SQLITE_OK)
{
// looping through existing return rows
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
// retreiving database values
users->user_id = sqlite3_column_int(sqlStatement,0);
users->user_name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 1)];
// adding verse object to the return data array
[returnData addObject:users];
}
}
else
{
// logging problem with prepare
NSLog(@"Problem with prepare statement: %s", sqlite3_errmsg(dbPointer));
return NO;
}
// returning number of rows in the array
return [returnData count];
}
//** Sample usage
// retreiving the number of users from the database
SQLiteFunctions *sql = [[SQLiteFunctions alloc] init];
Functions *func = [[Functions alloc] init];
// testing for successful open
if([sql openDatabase:@"users"])
{
// testing for that profile name existing already
if([sql getUserRecords:[func strCat:@"SELECT * FROM users;":nil:nil:nil:nil]] > 0)
{
int user_id;
NSString *user_name;
for(Users *myUser in sql->returnData)
{
user_id = myUser.user_id;
user_name = myUser.user_name;
// do other stuff with values
}
}
}