At the moment our API is returning NULL
for any int
parameters which don't have a value.
e.g. In our user API one of our parameters looks like this:
{
...
"user_id":NULL
...
}
I understand this can't be 0
as that could be a valid response, but having a NULL
pointer is causing all sorts of issues because int
s can't be NULL
pointers.
My thought was that these values should be left out altogether - then they would return nil
values (in objective c, e.g. [dictionary objectForKey:@"user_id"] == nil
) which seems more appropriate, and isn't checking for a null pointer (which seems wrong, there is a difference between an int and a pointer).
Otherwise, a work around would be to make it into an NSNumber
object which requires a pointer and can therefore be NULL
. Then I can do something like:
NSNumber *userID = [dictionary objectForKey:@"user_id"];
if(userID != [NSNull null]){
// its not null
}
But to me this feels fundamentally wrong, and the NSNumber
documentation says things like:
Note that number objects do not necessarily preserve the type they are created with.
This also makes me feel dirty.
(Then again, I'm initialising NSDecimalNumber
s with strings... so I don't know why this would bother me...).
If your "API" is expected to return an int
, then it should never return NULL. Like you already said, you could use NSNumber
, in that case you could return NULL. When talking about int
, NSNumber
will not come with loss of data, only in cases like irrational numbers the different type would matter.
So in short, if you want to return NULL/nil in some cases, you have to use an object type, NOT int
. If you feel better with using int
, then the only way would be to use special "invalid" values like -1
or -INT_MAX
to let the user know the value is invalid. Or you could throw an exception if that's an option - or just add another method to check if a valid response can be given.