reading unicode from sqlite and creating a NSString

做~自己de王妃 提交于 2019-12-01 13:23:19

问题


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!


回答1:


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




回答2:


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];
}


来源:https://stackoverflow.com/questions/4664335/reading-unicode-from-sqlite-and-creating-a-nsstring

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