How do I convert an NSString value to NSData?

8 Solutions Collect From Internet About “How do I convert an NSString value to NSData?”

NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

you can take reference from this link

Converting NSString like so will force a trailing \0 byte, which means NSJSONSerialization:JSONObjectWithData and others will fail unless you remove it.

I.e. do

NSData* data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

and then

data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];

then feel free to proceed with NSJSONSerialization:JSONObjectWithData.

In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)


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


let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String

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.

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

let myString = "test"
let myData = .utf8)
print(myData) // Optional(Data)
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];