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/