View Full Version : assign NSNumber to value of NSNumber
Sep 14, 2008, 06:17 PM
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?
Sep 14, 2008, 06:35 PM
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.
Sep 15, 2008, 04:48 AM
Since NSNumber is immutable you don't need to copy it, you can just retain it like so:
NSNumber *number2 = [number1 retain];