Search code examples
objective-cnumbersintegerprimitivensinteger

Handling integers in Objective-C


I was told by a developer that working with integers can be frustrating in Objective-C, so that he prefers to work directly with strings for IDs returned in JSON messages in order to save frequent conversions between integers and strings. In other words, he wants these IDs returned as strings by the API even if they are natively integers on the server. He also said that you cannot use integers in things like dictionary/map in Objective-C so that again strings are better (and he suggested that we should just use '1' instead of 1 as primary keys in DB tables so that the data types on both sides coincide).

I know little about Objective-C, but I find it hard to believe that such basic stuff can be this annoying in the language. From what I can gather, there are different types of 'numbers' in Objective-C:

  • int, float, double, long, and short (C primitives)
  • NSInteger, NSUInteger, CGFloat (Objective-C primitives)

EDIT: NSNumber is not a primitive, but a wrapper object type that stores and retrieves different primitive values. Thanks @rmaddy

The latter types seem to standardize APIs across different underlying architectures so that the developers don't need to care about things like 32-bit vs. 64-bit integers on different hardware.

Back to the complaint by my friend, for dealing with integer IDs returned from a web API, which data type should be used for storing them and using them in data structures such as a dictionary? Are said conversions inevitable?


Solution

  • Your friend is out of date by a few years. It used to be as bad as they make out (though still I wouldn't agree to putting everything into strings because of it).

    That has all been fixed with the modern Objective C syntax. This is a dictionary with some numbers in it:

    NSUInteger answer = 42;
    NSDictionary * dict = @{@"answerCount": @1,
                            @"value": @(answer)};
    

    Sure, it's not the nicest syntax one could have chosen, but it's perfectly workable.

    Also, there are a number of libraries for taking data from the wire, parsing the JSON, and exploding the result into model objects. This way you never really deal with raw JSON dictionaries. I'd strongly recommend investigating those options before you commit to a wire format.