iPhone crash with jsonData argument is NULL
iPhone client application crashed, when it received NULL as jsonData argument. Using third party JSONKit library, which has the following line of code:
- (id)objectWithData:(NSData *)jsonData error:(NSError **)error
{
if(jsonData =开发者_StackOverflow= NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
}
JSONKit documentation says:
Important: objectWithUTF8String: and mutableObjectWithUTF8String: will raise NSInvalidArgumentException if string is NULL.
Question: how should I handle this situation so that the iPhone application does NOT crash in this case? Not looking for theoretical exception handling code, but tips how do applications in general handle jsonData == NULL situation?
simple. abide by the library's rules, like so:
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];
...
It's pretty clear, when there's no data, the library raises an exception (NSException). If you're unfamiliar with the terms of exception handling, I suggest reading about it on wikipedia, and then on Apple's Doc, it's a pretty common programming subject.
As far as the issue goes, you need to catch the 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.
}
精彩评论