reading unicode from sqlite and creating a NSString

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″

  • Subscript: access my dictionary values with a String enumeration
  • Ambiguous use of 'subscript' with NSArray & JSON
  • Casting NSDictionary as Dictionary Swift
  • Ambiguous Use of Subscript in Swift
  • Swift Subscript Error
  • Is it possible to add “keyed-subscripting” to Class objects?
  • \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!

    2 Solutions Collect From Internet About “reading unicode from sqlite and creating a NSString”

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