views:

493

answers:

2

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!

+1  A: 

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).

warrenm
Will this work for reassigning NSNumbers?Also, as I posted in a comment to Ben, I can't seem to change the values even using @property (nonatomic, assign) with floats:((myViewController*)self.parentViewController).otherViewController.value = 1.0;doesn't seem to work with an assert statement right afterwards. Any ideas?
Peter Hajas
Yes, it will work for assigning/reassigning to `NSNumber` properties. Can you confirm in your most recent example that the `value` property is a value-type (like CGFloat, double, etc.) with the `assign` specifier? Are you `@synthesize` ing all of these properties or writing their accessors and mutators yourself?
warrenm
The value property is a float, and I'm using the @property (readwrite, assign) specifier. I'm synthesizing the properties. Here's what I was just playing with:((myViewController*)self.parentViewController).otherViewController.value = 1.0;assert(((myViewController*)self.parentViewController).otherViewController.value == 1.0);This statement fails. I'm really confused why it's happening.(also, how do I activate those slick little highlighted code blocks?)Thanks so much for your help!
Peter Hajas
I think we'd need to see all of your code to go further with this. I just ran some quick tests and I really can't see why that assert would fail unless there's a problem with the property declaration. As an issue of style, though, it's a bad idea to test for equality between floating point values, since they may differ slightly due to rounding errors and machine precision. Also, use backticks to do `inline formatting like this` (see the formatting guide for help).
warrenm
A: 

((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.

codewarrior