33

Is there a way to change the value contained in an NSNumber after it is created without making it point to a different NSNumber?

NSNumber *num = [NSNumber numberWithInt:0];
num = [NSNumber numberWithInt: 1]; // now num points to a different object, which I don't want.  I want it the same object still, but different value.

2 Answers 2

46

NSNumber is immutable. Actually, it's a subclass of NSValue, and all NSValues are immutable.

3
  • 2
    It is a bit odd that there is no NSMutableNumber Commented Jul 2, 2009 at 2:54
  • 1
    Not really, typically when you'd want a "mutable" number you end up using a primitive. NSNumber is more useful for serialization, being a dictionary key, and things along those lines. Commented Jul 2, 2009 at 3:05
  • 6
    @MarcCharbonneau there are definitely times when you want a number to be mutable. I just came across one... and ended up just storing my number in an NSMutableString instead (I couldn't be bothered defining my own class just to store a mutable integer in an immutable NSDictionary). Commented Dec 28, 2013 at 6:01
10

No, you can't change the value of NSNumber.

See, for example, this post.

Not the answer you're looking for? Browse other questions tagged or ask your own question.