iPhone 崩溃,jsonData 参数为 NULL

标签 iphone json

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 文档说:

Important: objectWithUTF8String: and mutableObjectWithUTF8String: will raise NSInvalidArgumentException if string is NULL.

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

最佳答案

简单。遵守图书馆的规则,如下所示:

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];
...

关于iPhone 崩溃,jsonData 参数为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226030/

相关文章:

iphone - 我们可以在 XCode 4.0 中放大/缩小 Xib 文件 View 吗?

iphone - 如何将 NSTimeInterval 转换为 int?

python - 使用 read_pickle 将 json_pickle(d) 推文读取到数据帧时发生 KeyError

javascript - 如何 console.log 此 JSON 对象的一个​​值?

java - 解析JSON对象: Call the constructor after parsing?

iphone - 我必须提供哪些选项才能提供允许对 UITableView 进行排序的功能?

ios - Xcode 12.5 调试器自 macOS Big Sur 11.3 起运行缓慢( native Swift 项目)

python - 如何在 Tensorflow 中读取 json 文件?

json - 如何将具有动态字段的 JSON 对象映射到 Go 结构

iphone - 将数据存储到 NSUserDefaults