johnezang / JSONKit

Objective-C JSON
6.21k stars 1.66k forks source link

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

Open tarbayev opened 12 years ago

tarbayev commented 12 years ago

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.

hanneshal commented 12 years ago

+1 for this solution

odyth commented 11 years ago

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.