如何将 NSString 值转换为 NSData?

如何将NSString值转换为NSData

答案

NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
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

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

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

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
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!
NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];