assign NSNumber to value of NSNumber

Discussion in 'Mac Programming' started by liptonlover, Sep 14, 2008.

  1. liptonlover macrumors 6502a

    Mar 13, 2008
    Yet another stupid question....

    NSNumber has things like initWithInt: etc., but there isn't an initWithNumber or initWithObject. Can I just do numberOne=numberTwo, or am I not seeing a crucial method?
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    NSNumber implements NSCopying, so you can call -copy to get a new NSNumber * that points to a new NSNumber instance with the same value. Don't use =, as that will just be pointer assignment, so both NSNumber *s will be pointing to the same NSNumber instance. That's probably OK since NSNumber is immutable, but you wouldn't want to have your original freed while depending on it with the new name.

    I don't know the intricacies here, so someone else might want to say if = results in an increment in the reference count. I don't think so.

  3. Bakerman macrumors member

    Jan 31, 2005
    Since NSNumber is immutable you don't need to copy it, you can just retain it like so:

    NSNumber *number2 = [number1 retain];

Share This Page