1

我无法从传递的结构中获取 char* 字符串。我有以下代码:

typedef struct {
    NSInteger id;
    char *title;
} Movie;

...

Movie movie = [self randomMovie];

NSInteger movieID = movie.id;
NSString *movieTitle = [NSString stringWithUTF8String:movie.title];
NSLog(@"movieTitle: %@", movieTitle);

...

- (Movie)randomMovie {
sqlite3_stmt *statement;
NSString *query = @"SELECT id, title FROM movies ORDER BY RANDOM() LIMIT 1;";

Movie movie;

if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
    if (sqlite3_step(statement) == SQLITE_ROW) {
        // Get the id and title of the first
        movie.id = sqlite3_column_int(statement, 0);
        movie.title = (char *)sqlite3_column_text(statement, 1);
    }
}

NSLog(@"Random movie %d title: %@", movie.id, [NSString stringWithUTF8String:movie.title]);

sqlite3_finalize(statement);
return movie;
}

这给了我输出:

2013-03-13 10:10:39.438 Fabflix[89156:c07] Random movie 872011 title: Ray
2013-03-13 10:10:39.439 Fabflix[89156:c07] movieTitle: (null)

有谁知道为什么标题字符串没有从 randomMovie 正确传递?谢谢!

4

2 回答 2

2

我对 sqlite3 C API 不是很熟悉,但是您确定sqlite3_finalize()调用不会破坏从返回的 C 字符串sqlite3_column_text()吗?你可能需要strdup()那个东西(然后再记住free()它)。

更新:是的,来自文档:

返回的指针在发生上述类型转换之前有效,或者直到调用 sqlite3_step() 或 sqlite3_reset() 或 sqlite3_finalize()。用于保存字符串和 BLOB 的内存空间会自动释放。

于 2013-03-13T17:20:24.103 回答
1

调用返回的内存sqlite3_column_text立即释放sqlite3_finalize。您需要先将该值复制到您自己的字符串中。

typedef struct {
    NSInteger id;
    NSString *title;
} Movie;

/* ... */

movie.title =
    [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
于 2013-03-13T17:21:47.097 回答