如何将NSString值转换为NSData?

如何将NSString值转换为NSData

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

你可以参考这个链接

像这样转换NSString将强制一个尾随的\0字节,这意味着NSJSONSerialization:JSONObjectWithData和其他将失败,除非你删除它。

就是这样

 NSData* data = [yourString dataUsingEncoding:NSUTF8StringEncoding]; 

接着

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

然后随意继续使用NSJSONSerialization:JSONObjectWithData

如果Swift Developer来到这里,

从NSString / String转换为NSData

 var _nsdata = _nsstring.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 

首先,你应该使用dataUsingEncoding:而不是通过UTF8String 。 当你在编码中需要一个Cstring时,你只使用UTF8String

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

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

 let myString = "test" let myData = myString.data(using: .utf8) print(myData) // Optional(Data) 
 NSString *str = @"hello"; NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];