如何将NSString值转换为NSData?


当前回答

迅速:

快5.倍

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

字符串到数据:

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

数据到字符串:

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

OBJECTIVE - C:

德国…

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

ns戴:

NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];

其他回答

objective - c:

NSString to NSData:

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

NSData to NSString:

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

迅速:

字符串到数据:

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

数据到字符串:

var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!

以防Swift开发者来这里,

将NSString / String转换为NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

首先,你应该使用dataUsingEncoding:而不是通过UTF8String。只有在需要该编码的C字符串时才使用UTF8String。

然后,对于UTF-16,在你的dataUsingEncoding:消息中传递NSUnicodeStringEncoding而不是NSUTF8StringEncoding。

对于Swift 3,你将主要从字符串转换为数据。

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

更新Swift 5.x

let str = "teststring"
let data = str.data(using: .utf8)