麻烦在Struct中传递C字符串

时间:2013-03-13 17:13:49

标签: ios objective-c string

我无法从传递的结构中获取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正确传递?谢谢!

2 个答案:

答案 0 :(得分:2)

我对sqlite3 C API并不十分熟悉,但是你确定sqlite3_finalize()调用没有破坏从sqlite3_column_text()返回的C字符串吗?您可能需要strdup()那件事(然后再记得free())。

更新:是的,来自文档:

  

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

答案 1 :(得分:1)

sqlite3_column_text is released as soon as you call sqlite3_finalize返回的内存。您需要先将值复制到您自己的字符串中。

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

/* ... */

movie.title =
    [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];