How do I convert an NSString value to NSData?

2019-01-02 16:43发布

How do I convert an NSString value to NSData?

10条回答
余生请多指教
2楼-- · 2019-01-02 17:02

Objective-C

NSString *str = @"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];

Swift

let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
查看更多
柔情千种
3楼-- · 2019-01-02 17:05
NSString *str = @"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

you can take reference from this link

查看更多
浪荡孟婆
4楼-- · 2019-01-02 17:06

In case of Swift Developer coming here,

to convert from NSString / String to NSData

var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
查看更多
看风景的人
5楼-- · 2019-01-02 17:07

First off, you should use dataUsingEncoding: instead of going through UTF8String. You only use UTF8String when you need a C string in that encoding.

Then, for UTF-16, just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.

查看更多
登录 后发表回答