Search code examples
objective-ccastingsqlitecharunsigned

Defined behavior of cast from unsigned char * to char * in Objective-C


I understand the difference between unsigned char * and char * types. I also understand how to use reinterpret_cast to cast an unsigned char * to a char * in C++.

I'm using sqlite3 in Objective-C and am trying to get an NSString from a call to

sqlite3_column_text(...);

To do this, I'm basically doing:

char *cParam = (char *)sqlite3_column_text(compiledStatementPtr, 0);
NSString *aParam = nil;
if (cParam) {
    aParam = [NSString stringWithUTF8String:cParam];
}

sqlite3_column_text(), however, returns an unsigned char * and I'm worried about the behavior of the cast to char *. I've read that the cast is implemenation specific and I was wondering if this is a safe cast in Objective-C or if I'm totally barking up the wrong tree?


Solution

  • You don't have much to worry about due to the cast. Actually, Apple sample code uses the exact same code pattern you are using:

    self.title =
      [NSString stringWithUTF8String:(char *)sqlite3_column_text(init_statement, 0)];
    

    (From SQLite Book List Book.m class).

    I think you should be more concerned with the database actually having UTF-8 strings.