tags:

views:

590

answers:

1

I have an sqlite string column that is assigned to a string. I need to make sure it isn't nil before assigning. I'm doing this:

char *isNil = sqlite3_column_text(selectstmt, 2);
if(isNil != nil){
  myName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 2)];}

which gives the warning:

warning: initialization discards qualifiers from pointer target type

What is the proper way to do it?

+2  A: 

You're getting the warning as you're ignoring the const. The API is defined:

const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);

You're assigning the return to a char*, so you're dropping the const. That is why you get the warning. You should respect the const.

const unsigned char *isNil = ...

I'm not really a huge objective-c guy, but I think stylistically it's common practice to compare primative types against NULL rather than nil. Also there is no need to call column_text twice.

const char *columnText = (const char *)sqlite3_column_text(selectstmt, 2);
if(columnText != NULL)
{
    myName = [NSString stringWithUTF8String: columnText ];
}

You can see above I've cast the const unsigned char pointer to a const signed char pointer. You should make sure you know when you cast away a warning that it is the right thing to do. In this case it is safe to cast to an signed char. In general, never cast away const though, as whoever made that API could be doing something that requires you to treat the data as const.

Andrew Barrett
Thanks. That gives a new warning on the assignment of *columnText:Pointer targets in initialization differ in signedness.
4thSpace
I've added the cast to stop the warning.
Andrew Barrett