Proper checking of nil sqlite text column

偶尔善良 提交于 2020-01-24 17:55:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/598396/proper-checking-of-nil-sqlite-text-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!