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

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 objectNSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

you can take reference from this link


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