views:

56

answers:

2

Hello,

I'm getting the following error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSString stringWithUTF8String:]: NULL cString'

on the line of code below:

NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];

I'm not sure whats going on here, the column I referenced in my SQL statement contains data. Full code below.

// 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
        const char *sqlStatement = "select ZROUTE_NAME from ZROUTE";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) 
        {
            // Loop through the results and add them to the Route Name array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) 
            {
                // Read the data from the result row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                // Add the animal object to the animals Array
                //[list addObject:animal];              
                [list addObject:aName];             
                //[animal release];
            }
        }
        else 
        {
            NSLog(@"Error: failed to select details from database with message '%s'.", sqlite3_errmsg(database));
        }

        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);        
    }
    sqlite3_close(database);
+1  A: 

Handle the NULL pointer condition for the statement

if((char*)sqlite3_column_text(compiledStatement, 1) != NULL)
{
      NSString *aName = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];
}

This will solve your problem.

Thanks,
Jim.

Jim
This has the exact same problem. You shouldn't check against the `NSString`, but the raw C string.
JoostK
Yeah my mistake. Now Corrected. Thanks JoostK.
Jim
Stephen
Same here, why call the function twice if you can store the result in a variable? @ste
Georg Fritzsche
check out my answer.
sugar
A: 

Ahhh :p - I believe - If you implement following statement, You would not in trouble.

This will never throw exception as you mentioned - * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSString stringWithUTF8String:]: NULL cString'

But remember - when there is empty value - your string would have (null) value

NSString *bName=[NSString stringWithFormat: @"%s",(char *)sqlite3_column_text(compiledStmt, 0)];

That's it. UpVote if found helpful. :)

sugar