Search code examples
objective-cmacrosnsnumberobjective-c-literals

@"" string type literals for NSNumber


I love the shorthand handling of string literals in Objective C with the @"string" notation. Is there any way to get similar behavior with NSNumbers? I deal with numbers more and it's so tedious having [NSNumber numberWithWhatever:] calls everywhere. Even creating a macro would work, but my knowledge of how best to do that is limited.


Solution

  • I'm using a macro like

    #define N(x) [NSNumber numberWithInt: x]
    

    wich leads to code like

    [N(123) intValue];
    

    update:

    One should be aware of the CPU and memory consumption of such a macro. While the @"…" strings are static compiler generated strings of the constant string class (depends on foundation maybe NSConstantString in Cocoa?) the macros create code which is evaluated at runtime and therefore create a new object every time they are called.