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 16:45
NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
查看更多
刘海飞了
3楼-- · 2019-01-02 16:51
NSString *str = @"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
查看更多
一个人的天荒地老
4楼-- · 2019-01-02 16:53

For Swift 3, you will mostly be converting from String to Data.

let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
查看更多
梦寄多情
5楼-- · 2019-01-02 16:54
NSString *str = @"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
查看更多
余欢
6楼-- · 2019-01-02 16:57

Do:

NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];

then feel free to proceed with NSJSONSerialization:JSONObjectWithData.


Correction to the answer regarding the NULL terminator

Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:

  1. As documented by dataUsingEncoding::

    Return Value

    The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument

  2. As documented by getCString:maxLength:encoding: and cStringUsingEncoding::

    note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator

查看更多
流年柔荑漫光年
7楼-- · 2019-01-02 16:57

Objective-C:

NSString *str = @"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Swift:

let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
查看更多
登录 后发表回答