Objective C convert number to NSNumber

前端 未结 5 585
情深已故
情深已故 2021-01-03 19:43

Why doesn\'t this please the compiler? Casting is supposed to work like in C as I can read here How to cast an object in Objective-C.

[p setAge:(NSNumber*)10         


        
相关标签:
5条回答
  • 2021-01-03 20:10

    In a sort of symmetry with your earlier question, NSNumber is an object type. You need to create it via a method invocation such as:

    [p setAge:[NSNumber numberWithInt:10]];
    

    Your current code is attempting simply to cast the arbitrary integer 10 to a pointer. Never do this: if the compiler didn't warn you about it, you would then be trying to access some completely inappropriate bytes at memory location 10 as if they were an NSNumber object, which they wouldn't be. Doing that stuff leads to tears.

    Oh, and just to preempt the next obvious issues, remember that if you want to use the value in an NSNumber object, you need to get at that via method calls too, eg:

    if ( [[p age] intValue] < 18 )
        ...
    

    (NSNumber is immutable, and I think it is implemented such that identical values are mapped to the same object. So it is probably possible to get away with direct pointer comparisons for value equality between NSNumber objects. But please don't, because that would be an inappropriate reliance on an implementation detail. Use isEqual instead.)

    0 讨论(0)
  • 2021-01-03 20:11

    Today it is also possible to do it using shorthand notation:

    [p setAge:@(10)];
    
    0 讨论(0)
  • 2021-01-03 20:12

    Because NSNumber is an object and "10" in a primitive integer type, much like the difference between int and Integer in Java. You, therefore, need to call its initialiser:

    [p setAge:[NSNumber numberWithInt:10]
    
    0 讨论(0)
  • 2021-01-03 20:25
    NSNumber *yourNumber = [NSNumber numberWithInt:your_int_variable];
    
    0 讨论(0)
  • 2021-01-03 20:27

    Use this:

    [p setAge:[NSNumber numberWithInt:10]];
    

    You can't cast an integer literal like 10 to a NSNumber* (pointer to NSNumber).

    0 讨论(0)
提交回复
热议问题