如何将NSString值转换为NSData?


当前回答

NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];

其他回答

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

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

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 = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];