950

How do I convert an NSString value to NSData?

Nick
  • 875
  • 6
  • 20

14 Answers14

1446
NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
ldiqual
  • 15,015
  • 6
  • 52
  • 90
flitzwald
  • 20,200
  • 2
  • 32
  • 28
  • What are the pros and cons of using UTF-8 as opposed to something higher like UTF-16 or UTF-32? – Albert Renshaw Jan 13 '14 at 02:34
  • 4
    The NSData doesn't care much about whether it is UTF-8 or UTF-16 or UTF-32. There are two problems: One, UTF-16 and UTF-32 need to have the right byte-ordering. Two, whoever converts it back to an NSString* must know the encoding, and often will assume UTF-8 encoding. Generally, UTF-8 is most likely to be handled correctly. – gnasher729 Mar 20 '14 at 17:50
  • 1
    @bendytree actually no it doesn't, -dataUsingEncoding: will return an non-null-terminated string which is what stringWithUTF8String: requires, you're bounds to read memory you don't want. What converts it back is: -initWithData:encoding:. – Psycho May 05 '14 at 17:38
  • 1
    @Albert Renshaw currently (no guarantee of things staying this way) `NSString` uses UTF-16 internally so there might be a slight performance gain because it does not have to do a UTF-16 <-> UTF-8 conversion. Personally, we prefer (as @gnasher729 suggests) robustness over performance and use UTF-8 everywhere. – Some Developer Oct 21 '14 at 01:32
  • macOS and my app are not running on big endian cpus, so I prefer utf16. – Tom Sep 16 '21 at 19:58
68
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

you can take reference from this link

Raptor
  • 53,206
  • 45
  • 230
  • 366
ALOK KUMAR
  • 745
  • 5
  • 7
  • 4
    One liner solution: `NSData *data = [@"helowrld" dataUsingEncoding:NSUTF8StringEncoding];` – Raptor May 27 '15 at 10:22
35

Do:

NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

then feel free to proceed with NSJSONSerialization:JSONObjectWithData.


Correction to the answer regarding the NULL terminator

Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:

  1. As documented by dataUsingEncoding::

    Return Value

    The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument

  2. As documented by getCString:maxLength:encoding: and cStringUsingEncoding::

    note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator

Cœur
  • 37,241
  • 25
  • 195
  • 267
Andrew Kolesnikov
  • 1,920
  • 1
  • 14
  • 20
  • 14
    This is WRONG! Please see my post here: http://stackoverflow.com/q/14087094/192819 – jpswain Dec 30 '12 at 00:06
  • 4
    Yup. `dataUsingEncoding:` does not return null-terminated data. Only `UTF8String` and other methods that return a C string return a null-terminated string. – Peter Hosey Dec 30 '12 at 01:51
  • @PeterHosey do you have any source for that? I am having a hard time finding that in any docs. – shortstuffsushi Jun 18 '15 at 18:05
  • @shortstuffsushi: The methods that take or return a C string are expressly documented so; for example: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instp/NSString/UTF8String You can verify this for other methods, such as `dataUsingEncoding:`, by inspecting the data's length and bytes. (Note that some encodings, such as UTF-16, will emit 0x00 bytes! But those aren't terminators; they're part of larger code units. And it is possible to have a U+0000, which will be encoded as such, but is not a terminator.) – Peter Hosey Aug 06 '15 at 06:25
  • @shortstuffsushi To wit: `const unichar buffer[1] = { 0x0000 }; NSString *string = [NSString stringWithCharacters:buffer length:1]; NSData *data = [string dataUsingEncoding:NSUTF16BigEndianStringEncoding]; NSLog(@"%lu %@", (unsigned long int)data.length, data);` – Peter Hosey Aug 06 '15 at 06:25
  • @shortstuffsushi And please do file bugs against the docs: https://bugreport.apple.com/ – Peter Hosey Aug 06 '15 at 06:27
  • 1
    Thanks @PeterHosey, the docs you linked there *do* explicitly state the lack of NULL termination -- `(note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator)`. I must have missed this earlier. I'll be sure to write up anything in the future, though. – shortstuffsushi Aug 06 '15 at 14:37
  • 1
    (For anyone who's wondering: shortstuffsushi's quote is under `cStringUsingEncoding:`. I was looking under `dataUsingEncoding:`.) – Peter Hosey Aug 21 '15 at 05:03
  • @jpswain the author of the post didn't visit StackOverflow in the past 4 years and the score of the answer is too high for a reversal, so I've made a clear correction directly. Maybe users with 20,000+ reputation could vote to delete the answer, as what is left correct is duplicate information from other answers. – Cœur Oct 29 '18 at 09:38
20

In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
18

Objective-C:

NSString *str = @"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Swift:

let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
Shamsiddin Saidov
  • 2,281
  • 4
  • 23
  • 35
  • Probably processor-intensive compared to the other methods, but very useful if you're accessing the file system for persistence – Stephen J Nov 28 '17 at 18:05
10

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 UTF-16, just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Jerry Thomsan
  • 1,409
  • 11
  • 9
7

For Swift 3, you will mostly be converting from String to Data.

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
jacks205
  • 545
  • 8
  • 19
7

Objective-C:

NSString to NSData:

NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

Swift:

String to Data:

var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)

Data to String:

var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
Nick
  • 875
  • 6
  • 20
6
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
Undo
  • 25,519
  • 37
  • 106
  • 129
Nex Mishra
  • 774
  • 7
  • 13
  • 5
    This answer is wrong when `str` contains code points larger than 127. This is because `str.length` gives the number of Unicode characters, not the number of bytes. For example, if `str` is `@"にほんご"`, `str.length` gives 4 while `str.UTF8String` actually contains 12 bytes. Even if you replace `str.length` by `strlen(str.UTF8String)`, it will still be wrong for the case where `str` contains the NULL character, such as `@"にほ\0んご"`. – Pang Feb 24 '16 at 06:56
  • A NSData object created in this way throw exeption when using with [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; – Blazej SLEBODA Feb 03 '17 at 07:21
5

Update Swift 5.x

let str = "teststring"
let data = str.data(using: .utf8)
AnLT
  • 569
  • 8
  • 22
4

Swift:

Swift 5.x

let myStringToConvert = "My String to Convert in Data"
let myData = myStringToConvert.data(using: .utf8)

String to Data:

var myStringToConvert = "My String to Convert in Data"
var myData = myStringToConvert.data(using: String.Encoding.utf8)

Data to String:

var backToMyString = String(data: myData!, encoding: String.Encoding.utf8) as String!

OBJECTIVE C:

NSString to NSData :

NSString* myStringToConvert= @"My String to Convert in Data";
NSData* myData=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

NSData to NSString :

NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];
Shunan
  • 3,165
  • 6
  • 28
  • 48
Anuj Saini
  • 59
  • 5
1
NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
Kamani Jasmin
  • 691
  • 8
  • 11
0

Objective-C

NSString *str = @"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

Swift

let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
Rohit Makwana
  • 4,337
  • 1
  • 21
  • 29
0

In Swift there is an API which returns a non-optional

let str = "teststring"
let data = Data(str.utf8)
vadian
  • 274,689
  • 30
  • 353
  • 361