how do I set the value of an NSNumber variable (without creating a new object) in objective-c?
Background
- I’m using Core Data and have a managed object that has an NSNumber (dynamic property)
- passing (by reference) this to another method which will update it
- not sure how to update it? if I allocate it another new NSNumber things don’t work, which I guess makes sense it’s then got a pointer to a different object not the core data object (I guess)
An NSNumber object isn’t mutable. This means that the only way to change a property containing a NSNumber is to give it a new NSNumber. To do what you want, you have three options:
1. Pass the Core Data object to the method and have it directly set the property.
Called as
[self updateNumberOf:theCoreDataObject];2. Have the update method return a new NSNumber and update it in the caller.
Called using:
3. Pass a pointer to a number variable and update it in the caller (I would only suggest this over option 2 if you need to return something else).
Called using:
I did not bother with memory management in any of these examples. Make sure you release/autorelease objects appropriately.
4. (from Greg’s comment) Similar to option 1, but passes the key to the update method to be more portable.
Called as
[self updateNumberOf:theCoreDataObject forKey:@"number"];