我的iPhone项目中有以下功能,效果很好......除非查询没有返回任何内容然后应用程序崩溃。调试很麻烦,根本没有激活任何断点!
我知道这是有效的,因为我传入了DB中的静态内容并返回一个值。
-(NSString *)getSomeText:(NSString *)toPass {
sqlite3 *database;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"sf.sqlite"];
int strLength = 0;
strLength = [toPass length];
if (strLength <3)
return @"Unknown";
NSString *MIDstr;
NSMutableString * toPass Copy = [NSMutableString stringWithString:toPass];
MIDstr = [toPassCopy substringWithRange:NSMakeRange(0, 3)];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
NSString *BaseSQL = [NSString stringWithFormat:@"select * from MIDS where MID = '%@'",MIDstr];
NSLog(BaseSQL);
const char *sqlStatement = [BaseSQL UTF8String];
//NSLog(BaseSQL);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *returnString = [NSString stringWithFormat:@"%@",aName];
return returnString;
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
答案 0 :(得分:4)
一个。如果 sqlite3_step 没有返回任何行,则会因为声明要返回NSString而崩溃,但是如果没有行则不返回任何行。 调用者将尝试从堆栈中读取NSString,从而最终取消引用垃圾。
要快速解决问题,请写下:
sqlite3_close(database);
return nil;
}
并确保调用者处理 nil 结果。
B /如果您执行拥有数据,您的代码永远不会调用 sqlite3_finalize 和 sqlite3_close ,因为您提前返回:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
[..]
return returnString;
答案 1 :(得分:0)
while (sqlite3_step(sqlstatement) == SQLITE_ROW ) { //Your code goes here } sqlite3_finalize(sqlstatement); sqlite3_close(databaseRefObj);
关闭数据库并在while循环后完成你的语句,这帮助了我,