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.
Boon
  • 40,656
  • 60
  • 209
  • 315

2 Answers2

45

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

mmc
  • 17,354
  • 2
  • 34
  • 52
  • 2
    It is a bit odd that there is no NSMutableNumber – Peter N Lewis Jul 02 '09 at 02: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. – Marc Charbonneau Jul 02 '09 at 03: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). – Abhi Beckert Dec 28 '13 at 06:01
11

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

See, for example, this post.

Community
  • 1
  • 1
Naaff
  • 9,213
  • 3
  • 38
  • 43