简体   繁体   中英

Change NSNumber value by allocating new NSNumber?

I understand that NSNumber is immutable, but I still have the need to change it in my app. I use it because it's an object, and therefore usable with @property (if I could, I would use float or CGFloat in a heartbeat, but sadly, I can't).

Is there any way to just overwrite the old NSNumber instance? I'm trying this:

NSNumber *zero = [[NSNumber alloc] initWithFloat:0.0];
myNSNumber = zero

but this doesn't change the value. This is a simplified version of my code, as I'm changing the root view controller's parameter (I know, not MVC-friendly). Still, the changing of the value should be the same assignment, right? Should I release myNSNumber first? What should I set the @property at for myNSNumber?

Thanks!

You can get an autoreleased instance of NSNumber using convenience methods such as numberWithDouble: or numberWithInteger: . No need to invoke alloc/init, especially if you're assigning to a property with the retain specifier (these automatically retain/release upon assignment).

((myViewController*)self.parentViewController).otherViewController.value

Psychic debugging tells me that one of the objects in this chain of properties is nil. My money is on parentViewController because I often forget to set parent properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM