将NSString转换为NSData强制尾随字节? [英] Does converting NSString to NSData force a trailing byte?

查看:137
本文介绍了将NSString转换为NSData强制尾随字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是回应这个不正确的答案:
http://stackoverflow.com/a/7894952/192819

This is in response to this incorrect answer: http://stackoverflow.com/a/7894952/192819

如下转换NSString:

Does converting NSString like this:

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

强制结尾的\0字节,表示

force a trailing \0 byte, which means

-[NSJSONSerialization:JSONObjectWithData:] 

你删除它。

推荐答案

不,它不。请看这个例子:

No, it does not. See this example:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"v1", @"k1", 
                      @"v2", @"k2",
                      nil];
NSLog(@"dict=%@", dict);

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];    

NSString *jsonAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSData *jsonDataFromString = [jsonAsString dataUsingEncoding:NSUTF8StringEncoding];

// DO NOT DO THIS:
// jsonDataFromString = [jsonDataFromString subdataWithRange:NSMakeRange(0, [jsonDataFromString length] - 1)];

NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonDataFromString options:0 error:nil];
NSLog(@"jsonObject=%@", jsonObject);

尝试一下,然后尝试使用不要这么做行取消注释。你会看到没有问题。

Try it, and then try it with the "DO NOT DO THIS" line uncommented. You will see there is no problem.

这篇关于将NSString转换为NSData强制尾随字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆