Вопрос

I have sqlite db and export some result with query

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)];

Then I put all in NSMutableArray

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

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

When I try to save al in file with this code

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

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

It stamps correctly in NSLog but in file saves only the last record not all array. Please help me!

Это было полезно?

Решение

You need to create the NSMutableArray once and make all additions to it.

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];
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top