JSONKit icon indicating copy to clipboard operation
JSONKit copied to clipboard

JSONDecoder objectWithData:error: throws unnecessary exception when data object has zero length.

Open tarbayev opened this issue 11 years ago • 2 comments

In method:

- (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]);
}

-[NSData bytes] returns nil, if the length of the receiver is 0.

This causes raising exception in:

- (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
{
  if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."];          }
  if(string     == NULL) { [NSException raise:NSInvalidArgumentException       format:@"The string argument is NULL."]; }

  return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error));
}

According to Apple's recommendations, a good practice would be to return nil when string is equal to NULL in second method and raising no exception. This will make behavior more stable.

tarbayev avatar Oct 19 '12 11:10 tarbayev

+1 for this solution

hanneshal avatar Oct 22 '12 13:10 hanneshal

Whats doubly frustrating is if you pass in an NSError pointer an exception is still thrown instead of setting the NSError pointer and returning nil.

odyth avatar Dec 28 '12 07:12 odyth