如何将NSString值转换为NSData?


当前回答

以防Swift开发者来这里,

将NSString / String转换为NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

其他回答

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 5.x

let str = "teststring"
let data = str.data(using: .utf8)
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

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 = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

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