如何查找 NSMutableData 无效的原因

发布于 2024-08-24 17:51:10 字数 506 浏览 6 评论 0 原文

我访问 RESTFUL 网址并返回结果。结果采用 JSON 格式。我通过以下方式将响应转换为字符串:

- (void)connectionDidFinishLoading:(NSURLConnection   *)connection {
NSString *json = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes] length:[self.receivedData length] encoding:NSUTF8StringEncoding];

json 变量的值为 0x0。当我将鼠标悬停在其上时,我会看到 >。我如何调试它以了解其无效的原因?我在 JSON 解析器中渲染通过浏览器返回的 JSON。检查结果很好。

通过在 URL 中输入 ID 来返回结果。其他 ID 返回结果没有问题。结果集相当大。

I access a RESTFUL url and get back results. The results are in JSON. I turn the response into a string via:

- (void)connectionDidFinishLoading:(NSURLConnection   *)connection {
NSString *json = [[NSString alloc] initWithBytes:[self.receivedData mutableBytes] length:[self.receivedData length] encoding:NSUTF8StringEncoding];

The json variable has a value of 0x0. When I mouse over it, I see <Invalid CFStringRef>. How can I debug this to tell why it is invalid? I render the JSON given back through the browser in A JSON parser. That checks out fine.

Results are given back by entering an ID in the URL. Other IDs return results without issue. The result set is fairly large.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

腹黑女流氓 2024-08-31 17:51:10

首先,我将使用 initWithData:encoding: 来设置 NSString。差别很小,但这种方法的存在是有原因的。

然后,我会对 self.receivedData 进行十六进制转储以查看其中实际内容。如果该数据未正确进行 UTF8 编码,则 initWithData:encoding: 将失败。

(Google for NSData hex dump 来查找其他人的实用函数来执行此操作)

我发现有时 Web 服务的编码很马虎。所以我通常会实现这样的后备:

NSString* html = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if (html == nil) {
    html = [[NSString alloc] initWithData: data encoding: NSISOLatin1StringEncoding];
    if (html == nil) {
        html = [[NSString alloc] initWithData: data encoding: NSMacOSRomanStringEncoding];
    }
}

令人遗憾的是,这是必需的,但许多 Web 服务没有正确编写或配置。

First I would use initWithData:encoding: to setup the NSString. Small difference, but that method is there for a reason.

Then, I would do a hexdump of self.receivedData to see what is actually in there. If that data is not properly UTF8 encoded then the initWithData:encoding: will fail.

(Google for NSData hex dump to find other people's utility functions to do this)

I have found that sometimes web services are sloppy with their encoding. So I usually implement a fallback like this:

NSString* html = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
if (html == nil) {
    html = [[NSString alloc] initWithData: data encoding: NSISOLatin1StringEncoding];
    if (html == nil) {
        html = [[NSString alloc] initWithData: data encoding: NSMacOSRomanStringEncoding];
    }
}

It is kind of sad that this is required but many web services are not written or configured properly.

巡山小妖精 2024-08-31 17:51:10

使用 NSLog 查看字节。

Use NSLog to look at the bytes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文