Search code examples
iphoneiosxcodefmdb

I can't trap FMDB empty resultset


I am having trouble trapping an empty result set from FMDB. The code is below. I am getting NSLog's from the database opening and closing and NSLog "1" but none of the ones in the If statement! If I have data in the database its fine, but I want to trap and edit result if the database is empty.

    [self openDatabase];

NSNumberFormatter *nfcurrency = [[NSNumberFormatter alloc]init];
[nfcurrency setNumberStyle:NSNumberFormatterCurrencyStyle];
[nfcurrency setLocale:[NSLocale currentLocale]];

FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
//FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
NSLog(@"1");
if (result == NULL) {
    NSLog(@"Last BFNeeded Result = nil");
} else {
    while ([result next]) {
        NSLog(@"HERE");
        NSString *lastBFNeeded = [nfcurrency stringFromNumber:[NSNumber numberWithDouble:[result doubleForColumn:@"BFNeeded"]]];
        NSLog(@"lastBFNeeded=%@",lastBFNeeded);
    }
}

NSLog(@"ClosingDB");
[self closeDatabase];

Continuing after getting first reply:

I can't get hasAnotherRow to work as expected. I have this code:

FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 0,1;"];

if (result == nil) {
    NSLog(@"Last BFNeeded Result = nil");
}
else {
    NSLog(@"has results1: %@", [result hasAnotherRow] ? @"YES" : @"NO");
    while ([result next]) {
        NSLog(@"has results2: %@", [result hasAnotherRow] ? @"YES" : @"NO");
    }
}

With a database that returns a result, I get result1 NO, result2 YES so I assume the hasAnotherRow must go inside the while ([result next]) loop. However with an empty database, I get result1 NO and it doesn't even get to result2!


Solution

  • the "result" will never be nil for a query that produces 0 rows.

    also, you shouldn't compare object pointers to NULL -- compare to nil. See this question: NULL vs nil in Objective-C

    try this:

    FMResultSet *result = [[self getDatabase]executeQuery:@"SELECT BFNeeded FROM tblBets ORDER BY pk DESC LIMIT 1,1;"];
    
    NSLog ( @"has results: %@", [result hasAnotherRow] ? @"YES" : @"NO" );