2

Sometimes JSON returns (null) from the database where it gets data, so I do a check to see if its has returned that (null).

else if (NSOrderedSame == [[clubsArray objectAtIndex:indexPath.row] compare:@"(null)"] )

But Xcode is warning me

Incompatible Objective-C types 'struct NSString *', expected 'struct NSNumber *' when passing argument 1 of 'compare:' from distinct Objective-C type

I add NSStrings into that array so I'm confused as to why its talking about a struct.

NSString *clubNameReturned = [message objectForKey:@"clubname"];
[clubsArray addObject:clubNameReturned];

Is anybody able to shed some light on what's going on here?

The code executes as I expect it to, but I don't want to be doing something that's not correct.

jscs
  • 63,694
  • 13
  • 151
  • 195

4 Answers4

5

JSON does not return the "(null)" string. This string "(null)" is only what is displayed on the console when you NSLog the null singleton object (it's description representation).

Compare against [NSNull null] instead, which is a singleton especially used to store something that represent the null/nil value on containers.

AliSoftware
  • 32,623
  • 6
  • 82
  • 77
  • You have this wrong: `NSLog(@"%@", nil);` prints `(null)` and `NSLog(@"%@", [NSNull null]);` prints ``. – jscs Jun 20 '11 at 20:05
1

That is because the definition of the compare: method is:

- (NSComparisonResult)compare:(NSNumber *)otherNumber;

So it is expecting an NSNumber object, but you are passing an NSString.

If you want to check if 2 NSStrings are the same use the isEqualToString: method:

else if ([[clubsArray objectAtIndex:indexPath.row] isEqualToString:@"(null)"])

However it is likely not a string being returned (although that's what you see when it's printed to the console), so instead you should do:

else if ([clubsArray objectAtIndex:indexPath.row] == [NSNull null])
Jonathan.
  • 53,997
  • 54
  • 186
  • 290
0

The warning will go away if you explicitly downcast, e.g.:

if (NSOrderedSame == [(NSString *)[clubsArray objectAtIndex:indexPath.row] compare:@"(null)"] )

What happens is that you're calling the compare: method on the result of [clubsArray objectAtIndex:indexPath.row], which is of type id. Now, implicit downcasting is allowed from id to any other type... but in your case, the compiler cannot tell the exact type you want. Is it NSNumber or NSString or NSDate...? (BTW, NSObject does not respond to compare:). This is a warning because the compiler thinks you will provide the correct types during runtime (which you do!), but it tells you that you should be more explicit with that kind of code.

octy
  • 6,525
  • 1
  • 28
  • 38
0

I suggest you make use of this category on NSDictionary for dealing with null values in JSON data:

TouchJSON, dealing with NSNull

Community
  • 1
  • 1
Wolfgang Schreurs
  • 11,779
  • 7
  • 51
  • 92