Search code examples
objective-cxcode5

Xcode - NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString'


I have the below code that should populate the TableViewController with information from my sqlite file, it lets me add fine, and i can view the file and the information is there, but I'm getting the above error message, and failing miserably at fixing it....

-(NSMutableArray *) stockList
{

NSString *filePath = [self getWritableDBPath];

if(sqlite3_open([filePath UTF8String], &db) == SQLITE_OK)
{

    const char *sql = "Select Description, Quantity from StockTable";
    sqlite3_stmt *sqlStatement;
    if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
    {
        NSLog(@"Problem with query: %s", sqlite3_errmsg(db));
    }
    else
    {
        while (sqlite3_step(sqlStatement)==SQLITE_ROW)
        {
            Stock * stock = [[Stock alloc] init];

            stock.desc = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,     1)];
            stock.qty = [NSString stringWithUTF8String:(char *)     sqlite3_column_text(sqlStatement, 2)];

            [thestock addObject:stock];
            stock = nil;
        }
    }
    sqlite3_finalize(sqlStatement);
}
sqlite3_close(db);
return thestock;
}

thanks for any help, currently googling it myself..

connection strings as mentioned below: (reason being it causes a LINK error and states that MyDB is a duplicate in both views)

TableView:

NSString * MyDB2=@"StockDatabase.db";

AddingView:

NSString * MyDB=@"StockDatabase.db";

Solution

  • One (or both) of the columns you are fetching from the database is NULL:

    stock.desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement, 1)];
    stock.qty = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement, 2)];
    

    Guard against that with:

    const char *desc = sqlite3_column_text(sqlStatement, 1);
    if (desc)
        stock.desk = @(desc);
    const char *qty = sqlite3_column_text(sqlStatement, 2);
    if (qty)
        stock.qty = @(qty);