如何将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

以防Swift开发者来这里,

将NSString / String转换为NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

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)