我认为这应该如何工作存在一些基本的误解,我将不胜感激。我一直在尝试编写一些函数,这些函数将从 sqlite 表中提取数据,将其放入对象中,然后将该对象保存到数组中。然后该数组将被其他例程访问。这门课还有很多我不想阻塞论坛的内容。我遇到的问题是:
1)我似乎只能访问放入数组的最终值。我是否将“用户”对象错误地保存到数组中?
2)假设我在数组中正确获取了对象,我是否正确地将它们拉出?我在底部添加了一个示例拉程序。
3)任何有更多经验的人都可以提到一种更有效的方法吗?我仍在努力让我的 xcode 编程腿在我身下,并希望有任何关于编写更简洁代码的建议。
// **SQLiteFunctions 标头
#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 实现
-(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];
}
//** 示例用法
// 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
}
}
}