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

How do I convert an NSString value to NSData?

This question is related to ios objective-c nsstring nsdata

The answer is


In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

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

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

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


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!

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

you can take reference from this link


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)

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)

NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

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.


Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to nsstring

NSRange to Range<String.Index> Creating NSData from NSString in Swift How do I check if a string contains another string in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How do I URL encode a string Objective-C and Swift URL encoding Convert an NSURL to an NSString Remove all whitespaces from NSString

Examples related to nsdata

Convert UIImage to NSData and convert back to UIImage in Swift? Creating NSData from NSString in Swift How to initialise a string from NSData in Swift Convert between UIImage and Base64 string convert UIImage to NSData Convert NSData to String? Convert UTF-8 encoded NSData to NSString How do I convert an NSString value to NSData?