NSMutableArray丢失了所有对象

时间:2014-03-01 16:09:59

标签: ios iphone objective-c sqlite nsmutablearray

我正在创建一个函数,允许您从数据库中读取数据,然后将数据放入NSMutableArray,稍后将为用户返回该数据。虽然由于某种原因,当它要返回数据时,数据将从数组中删除。以下是该函数的代码:

+(NSMutableArray *) readFromDataBaseWithName:(NSString *)name withSqlStatement:(NSString *)sql {
    sqlite3 *database;
    NSMutableArray *rtn = [[NSMutableArray alloc] init];
    NSMutableArray *new = [[NSMutableArray alloc] init];
    int index = 0;
    NSString *filePath = [self copyDatabaseToDocumentsWithName:name];
    if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
        const char *sqlStateMent = [sql cStringUsingEncoding:NSASCIIStringEncoding];
        sqlite3_stmt *compiledStatement;
        if (sqlite3_prepare(database, sqlStateMent, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // loop through elements in row and put them into array
                const char *s = (char *)sqlite3_column_text(compiledStatement, index);
                while (s) {
                    [new addObject:[NSString stringWithUTF8String:s]];
                    index++;
                    s = (char *)sqlite3_column_text(compiledStatement, index);
                }
                [rtn addObject:new];
                [new removeAllObjects];
            }
        }
        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);
    return rtn;
}

非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

您不断重复使用new。您需要每次都创建单独的数组。

+(NSMutableArray *) readFromDataBaseWithName:(NSString *)name withSqlStatement:(NSString *)sql {
    sqlite3 *database;
    NSMutableArray *rtn = [[NSMutableArray alloc] init];
    int index = 0;
    NSString *filePath = [self copyDatabaseToDocumentsWithName:name];
    if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
        const char *sqlStateMent = [sql cStringUsingEncoding:NSASCIIStringEncoding];
        sqlite3_stmt *compiledStatement;
        if (sqlite3_prepare(database, sqlStateMent, -1, &compiledStatement, NULL) == SQLITE_OK) {
            while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // loop through elements in row and put them into array
                NSMutableArray *new = [[NSMutableArray alloc] init];
                const char *s = (char *)sqlite3_column_text(compiledStatement, index);
                while (s) {
                    [new addObject:[NSString stringWithUTF8String:s]];
                    index++;
                    s = (char *)sqlite3_column_text(compiledStatement, index);
                }
                [rtn addObject:new];
            }
        }
        sqlite3_finalize(compiledStatement);
    }
    sqlite3_close(database);
    return rtn;
}