开发者

reading unicode from sqlite and creating a NSString

开发者 https://www.devze.com 2023-02-04 10:50 出处:网络
Im working on an iOS app where I need to store and retrieve from an SQLite DB, a representation of a NSString that has subscripts. I can create a NSString at compile time with a constant:

Im working on an iOS app where I need to store and retrieve from an SQLite DB, a representation of a NSString that has subscripts. I can create a NSString at compile time with a constant:

@"Br\u2082_CCl\u2084"

\u2082 is a 2 subscript, \u2084 is a 4 subscript. What im storing in the SQLite db is:

"Br\u2082_CCl\u2084"

开发者_运维知识库

But what I can not figure out how to do, is reconvert that back into an NSString. The data comes back from the db as a char * "Br\\u2082_CCl\\u2084" Stripping out the extra slash has made no difference in my feeble experiments. I need a way get that back into an NSString - Thanks!


You need one of the NSString stringWithCString class methods or the corresponding initWithCString instance methods.


I solved the problem like this - error checking removed for clarity -

the unicode string comes into the parameter stringEncoded from the db like:

"MgBr\u2082_CH\u2082Cl\u2082"

+(NSString *)decodeUnicodeBytes:(char *)stringEncoded {
  unsigned int    unicodeValue;
  char            *p, buff[5];
  NSMutableString *theString;
  NSString        *hexString;
  NSScanner       *pScanner;

  theString = [[[NSMutableString alloc] init] autorelease];
  p = stringEncoded;

  buff[4] = 0x00;
  while (*p != 0x00) {

    if (*p == '\\') {
      p++;
      if (*p == 'u') {
        memmove(buff, ++p, 4);

        hexString = [NSString stringWithUTF8String:buff];
        pScanner = [NSScanner scannerWithString: hexString];
        [pScanner scanHexInt: &unicodeValue];

        [theString appendFormat:@"%C", unicodeValue];
        p += 4;
        continue;
        }
      }

    [theString appendFormat:@"%c", *p];
    p++;
    }

  return [NSString stringWithString:theString];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号