如果没有返回行,iPhone SQLite 查询会崩溃

标签 iphone sqlite

我的 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_finalizesqlite3_close,因为您提前返回:

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    [..]
    return returnString;

关于如果没有返回行,iPhone SQLite 查询会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2036529/

相关文章:

iphone - uitableview内容大小问题

javascript - 如何在浏览器窗口较小时显示滚动条?

iphone - rec、av基础框架的循环持续时间

java - 使用 SQLite DB 打开+读取,但获取空值?

c# - 使用 System.Data.Sqlite 进行 Sqlite 在线备份

c - SQLite3 : non-ascii characters not updated correctly?

iphone - 在一个选项卡栏项目内切换 Controller

ios - 如何在 iOS 应用程序中对 2 个不同的 Google 帐户进行 oAuth

php - pdo sqlite 找不到驱动程序...未处理 php 文件

reactjs - 具有持久本地数据库的渐进式 Web 应用程序