Proper checking of nil sqlite text column

2019-07-20 14:56发布

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?

标签: iphone sqlite
1条回答
叛逆
2楼-- · 2019-07-20 15:56

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.

查看更多
登录 后发表回答