如何将NSString值转换为NSData?


当前回答

objective - c:

NSString to NSData:

NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

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!

其他回答

以防Swift开发者来这里,

将NSString / String转换为NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

更新Swift 5.x

let str = "teststring"
let data = str.data(using: .utf8)

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 to NSData:

NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

NSData to NSString:

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!

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

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