我的 iPhone 项目中有以下功能,效果很好......除非查询返回任何内容,然后应用程序崩溃。在没有任何断点被激活的情况下进行调试是一件痛苦的事情!
我知道这是有效的,因为我传入数据库中的静态内容并返回一个值。
-(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);
}
最佳答案
A.如果 sqlite3_step 不返回任何行,则会崩溃,因为您已声明要返回 NSString,但是当没有行时,您不会返回任何内容。 调用者将尝试从堆栈中读取 NSString,从而最终取消引用垃圾。
要快速解决问题,请编写:
sqlite3_close(database);
return nil;
}
并确保调用者处理nil结果。
B/如果您确实有数据,您的代码永远不会调用sqlite3_finalize和sqlite3_close,因为您提前返回:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
[..]
return returnString;
关于如果没有返回行,iPhone SQLite 查询会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036529/