代码之家  ›  专栏  ›  技术社区  ›  Lee Armstrong

如果没有返回行,iphone sqlite查询将崩溃

  •  3
  • Lee Armstrong  · 技术社区  · 16 年前

    我的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);
    
    }
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   diciu    16 年前

    A.如果 sqlite3_步骤 调用方将尝试从堆栈中读取NSString,从而最终取消对垃圾的引用。

        sqlite3_close(database);
        return nil;
    }
    

    并确保来电者处理 结果。

    如果你 sqlite3_最终确定 sqlite3_关闭 因为你回来得早:

    while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
        [..]
        return returnString;
    
        2
  •  0
  •   Radix    13 年前
    while (sqlite3_step(sqlstatement) == SQLITE_ROW )
                {
                    //Your code goes here
    
                }
    
                sqlite3_finalize(sqlstatement);
                sqlite3_close(databaseRefObj);
    

    关闭数据库并在while循环后完成您的语句这帮了我的忙,

    推荐文章