Iphone sqlite query fails if rows are not returned

I have the following function in my iPhone project that works fine ... if the request returns nothing, then the application will work. It hurts to debug when none of the breakpoints is activated at all!

I know this works when I pass static stuff that is in the DB and it returns a value.

-(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);

}
+3
source share
2 answers

. sqlite3_step , , , NSString, , . NSString , , .

, :

    sqlite3_close(database);
    return nil;
}

, nil.

B/ , sqlite3_finalize sqlite3_close, :

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
    [..]
    return returnString;
+4
while (sqlite3_step(sqlstatement) == SQLITE_ROW )
            {
                //Your code goes here

            }

            sqlite3_finalize(sqlstatement);
            sqlite3_close(databaseRefObj);

while, ,

0

Source: https://habr.com/ru/post/1727928/


All Articles