【问题标题】:iPhone crash with jsonData argument is NULL带有 jsonData 参数的 iPhone 崩溃为 NULL
【发布时间】:2011-08-29 04:21:52
【问题描述】:

iPhone 客户端应用程序在收到 NULL 作为 jsonData 参数时崩溃。使用第三方JSONKit库,代码如下:

- (id)objectWithData:(NSData *)jsonData error:(NSError **)error
{
  if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
  return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
}

JSONKit 文档说:

重要提示:如果 string 为 NULL,objectWithUTF8String: 和 mutableObjectWithUTF8String: 将引发 NSInvalidArgumentException。

问题:我应该如何处理这种情况,以便 iPhone 应用程序不会在这种情况下崩溃?不是找理论上的异常处理代码,而是提示应用程序一般如何处理 jsonData == NULL 的情况?

【问题讨论】:

  • 通过确保数据不为空????
  • 很好的答案,除了我无法访问服务器:)
  • 但是您不需要访问服务器来确定字符串是否为空...

标签: iphone json


【解决方案1】:

简单。遵守图书馆的规定,像这样:

if (jsonData == nil) {
    assert(0 && "there was an error upstream -- handle the error in your app specific way");
    return; // not safe to pass nil as json data -- bail
}

// now we are sure jsonData is safe to pass

NSError * error = nil;
id ret = [json objectWithData:jsonData error:&error];
...

【讨论】:

  • 同意。图书馆就是这样,所以在它成为问题之前处理这种情况。谢谢!
【解决方案2】:

很明显,当没有数据时,库会引发异常 (NSException)。如果你不熟悉异常处理的术语,我建议reading about it on wikipedia,然后Apple's Doc,这是一个很常见的编程主题。

就问题而言,您需要catch exception

@try
{
    // Do whatever you're doing with the JSON library here.
}
@catch (NSException *exception)
{
    // Something happend
    if ([exception.name isEqualToString:NSInvalidArgumentException])
    {
        // This must be the jsonData == NULL.
    }
}
@finally
{
    // Optional, you can clear things here.
}

【讨论】:

  • 很好的答案,但在这种特定情况下没有帮助。我想我应该更清楚一点,这不是关于理论上的异常处理,而是如何处理这种现实生活中的情况:数据为 NULL,不能崩溃,该怎么办。恐怕不熟悉 JSON。
  • 然后,在 github 上 fork JSONKit 并提交你的补丁 J
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多