assign NSNumber to value of NSNumber

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

  1. macrumors 6502a

    Joined:
    Mar 13, 2008
    #1
    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?
    Nate
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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.

    -Lee
     
  3. macrumors member

    Joined:
    Jan 31, 2005
    Location:
    Sweden
    #3
    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