ios - How do I convert an NSString value to NSData?

ID : 1611

viewed : 182

Tags : iosobjective-cnsstringnsdata

Top 5 Answer for ios - How do I convert an NSString value to NSData?

vote vote


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


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

you can take reference from this link

vote vote



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

vote vote


In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding) 
vote vote



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 

Top 3 video Explaining ios - How do I convert an NSString value to NSData?