1

我已经搜索了几天的解决方案,不幸的是找不到任何适合我的应用程序需求的相关信息。

我要做的是:
调用一个 sqLite 查询方法
方法查询 sqLite 表(选择所有列)
将选定的行和列保存在数组
数组中必须返回给调用者
UITableView 必须显示返回的值

我的代码:

FirstViewController.m:

result = [queryObject myQueryMethod]; //result is of type NSMutableArray  

查询.m:

NSString *myUsername;  
NSString *from;  
NSString *to;  
NSString *message;  

querySQL = [NSString stringWithFormat:@"SELECT * FROM messages WHERE to = '%@'" , myUsername];  
query_stmt = [querySQL UTF8String];  

NSMutableArray *allMessages = [[NSMutableArray alloc] init];  
if(sqlite3_prepare_v2(_userDB, query_stmt, -1, &statement, NULL) == SQLITE_OK ) {  

        while (sqlite3_step(statement) == SQLITE_ROW) {  
            from = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];  
            to = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];  
            message = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];  
            [allMessages addObject:message];  //MY PROBLEM..
        }

        return allMessages; //return to caller in FirstViewController.m

    }  

我的问题是:如何将所有列(三)添加到数组中,并将数组返回给 FirstViewController.m 中的调用者,以便对 UITableView 的索引进行排序?
要在表格视图中显示信息,我使用:

cell.textLabel.text = [result objectAtIndex:indexPath.row];  

如果能得到任何帮助,我将不胜感激,谢谢!

4

2 回答 2

2

要保留所有 3 列的值,您应该使用字典。

while (sqlite3_step(statement) == SQLITE_ROW)
 {  
      from = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];  
      to = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];  
      message = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];  

      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: from, @"From", to, @"To", message, @"Message", nil];
      [allMessages addObject:dict];  //MY PROBLEM..
}

现在在获取值时,从字典中获取它:

cell.textLabel.text = [[result objectAtIndex:indexPath.row] objectForKey:@"To"];
于 2013-03-15T16:32:02.570 回答
0

您只是将消息值添加到数组中。您应该为三列中的每一列创建一个具有属性的对象,并改为返回这些对象的数组。

或者,您可以将三个字符串添加到数组并根据其位置检索每个值:

cell.textLabel.text = [result objectAtIndex:indexPath.row * 3];
NSString *to = [result objectAtIndex:indexPath.row * 3 + 1];
NSString *message = [result objectAtIndex:indexPath.row * 3 + 2];

当然,您需要将其他值添加到数组中:

[allMessages addObject:from];  //MY PROBLEM..
[allMessages addObject:to];
[allMessages addObject:message];
于 2013-03-15T16:39:20.317 回答