如何将NSString值转换为NSData?


当前回答

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

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

其他回答

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

你可以从这个链接得到参考

在Swift中,有一个返回非可选参数的API

let str = "teststring"
let data = Data(str.utf8)

迅速:

快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];

更新Swift 5.x

let str = "teststring"
let data = str.data(using: .utf8)
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];