How do I convert NSString to NSData?

17,117

First off, you should use dataUsingEncoding: instead of going through UTF8String. You only use UTF8String when you need a C string in that encoding.

Then, for “Unicode” (specifically, UTF-16), just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.

Share:
17,117

Related videos on Youtube

Steve McLeod
Author by

Steve McLeod

Java is my thing. I run Barbary Software, a tiny software company in Barcelona, Spain. Our products are Feature Upvote, a SaaS tool for feature request tracking, and Saber Feedback, a feedback widget for any website.

Updated on June 04, 2022

Comments

  • Steve McLeod
    Steve McLeod almost 2 years

    I have this line of code to convert NSString to NSData:

    NSData *data = [NSData dataWithBytes:[message UTF8String] length:[message lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    

    How do I do this in Unicode instead of UTF8? My message may contain cyrillic characters or diacritical marks.

    • Joachim Sauer
      Joachim Sauer over 14 years
      Define "Unicode". It's not an encoding (not strictly speaking at least). UTF-8 is perfectly capable of encoding all Unicode characters, so it should be sufficient for your use.