提问



如何将NSString值转换为NSData?

最佳参考


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

其它参考1


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


你可以参考这个链接[29]

其它参考2


像这样转换NSString会强制拖尾\0字节,这意味着NSJSONSerialization:JSONObjectWithData而其他字符将失败,除非你将其删除。


即做


NSData* data = [yourString dataUsingEncoding:NSUTF8StringEncoding];


接着


data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];


然后随意进行NSJSONSerialization:JSONObjectWithData

其它参考3


如果Swift Developer来到这里,


从NSString/String转换为NSData


var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)

其它参考4


目标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

其它参考5


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


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

其它参考6


NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];

其它参考7


对于Swift 3,你将主要从String转换为Data


let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)

其它参考8


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

其它参考9


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)