将NSMutableArray的所有内容保存在iOS文件中

时间:2013-11-23 16:28:36

标签: ios iphone sqlite writetofile

我有sqlite db并使用查询

导出一些结果
sqlite3 *MyDB;
const char *dbpath = [StringPathDB UTF8String]; // Convert NSString to UTF-8
NSString *querySQL = @"select * from chat order by id desc limit 20";



if (sqlite3_open(dbpath, &MyDB) == SQLITE_OK)
{

    const char *sql = [querySQL UTF8String];

    sqlite3_stmt *searchStatement;

    if (sqlite3_prepare_v2(MyDB, sql, -1, &searchStatement, NULL) == SQLITE_OK)
    {
        while (sqlite3_step(searchStatement) == SQLITE_ROW)
        {
            NSString *nickname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];
            NSString *time = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 1)];
            NSString *text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 2)];

然后我将所有内容放入NSMutableArray

NSMutableArray *list = [[NSMutableArray alloc] init];

[list addObject:nickname];
[list addObject:time];
[list addObject:text];

当我尝试使用此代码保存al文件时

for(int i = 0; i < [list count]; i++) {

                    NSLog(@"%@",list);
                   [list writeToFile:filePATH atomically:YES];
                   break;
                }

它在NSLog中正确标记但在文件中仅保存最后一条记录而不是所有数组。 请帮帮我!

1 个答案:

答案 0 :(得分:0)

您需要创建一次NSMutableArray并对其进行所有添加。

NSMutableArray *list = [[NSMutableArray alloc] init];
while (sqlite3_step(searchStatement) == SQLITE_ROW)
{
    NSString *nickname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];
    NSString *time = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 1)];
    NSString *text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 2)];
    [list addObject:nickname];
    [list addObject:time];
    [list addObject:text];
    ...
}
[list writeToFile:filePATH atomically:YES];