Search code examples
objective-cwarningsnsnumber

Warning: Converting to Boxing Syntax requires casting 'long' to 'int'


Any idea how to get this warning to go away. The code runs fine, I just don't like warnings in my project. I have never come across this warning before so I am making a mountain out of a mole hill I think. Boxing syntax? Is that referring to the square brackets? This warning shows up when trying to modernize an old project in Objective-C using Xcode.

for (int i = 0; i <= 6; i++) {

   [sequence addObject:[NSNumber numberWithInt:random()% 6]]; 

}

It throws an error stating:

Converting to boxing syntax requires casting 'long' to 'int'

enter image description here


Solution

  • "Boxing" refers to the new syntax for boxing C expressions, e.g.

    NSNumber *n = @(2*3+4)
    

    instead of

    NSNumber *n = [NSNumber numberWithInt:(2*3+4)];
    

    (see http://clang.llvm.org/docs/ObjectiveCLiterals.html for details).

    In your case,

    [NSNumber numberWithInt:random()% 6]
    

    creates a number object containing an int, but

    @(random()% 6)
    

    would create a number object containing a long, because random() is declared as

    long random(void);
    

    So to get exactly the same behavior as before the conversion, you would have to write

    [NSNumber numberWithInt:(int)(random()% 6)]
    

    which is then converted to

    @((int)(random()% 6))
    

    If you don't care which "flavor" of number object you get, then just convert that line manually to

    [sequence addObject:@(random()% 6)];
    

    but Xcode cannot decide that for you.