如何将NSString值转换为NSData?


当前回答

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

其他回答

objective - c:

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

objective - c

NSString *str = @"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

斯威夫特

let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

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

迅速:

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