Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I set the value of an NSNumber variable (without creating a new object) in objective-c

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)
like image 683
Greg Avatar asked May 11 '11 21:05

Greg


1 Answers

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.

- (void)updateNumberOf:(MyCoreDataObject *)theObject {
    NSNumber *newNumber = ...; // create new number
    theObject.number = newNumber;
}

Called as [self updateNumberOf:theCoreDataObject];

2. Have the update method return a new NSNumber and update it in the caller.

- (NSNumber *)updateNumber:(NSNumber *)oldNumber {
    NSNumber *newNumber = ...; // create new number
    return newNumber;
}

Called using:

NSNumber *theNumber = theCoreDataObject.number;
theNumber = [self updateNumber:theNumber];
theCoreDataObject.number = theNumber;

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

- (void)updateNumber:(NSNumber **)numberPointer {
    if(!numberPointer) return; // or possibly throw an error
    NSNumber *oldNumber = *numberPointer;
    NSNumber *newNumber = ...; // create new number
    *numberPointer = newNumber;
}

Called using:

NSNumber *theNumber = theCoreDataObject.number;
[self updateNumber:&theNumber];
theCoreDataObject.number = theNumber;

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.

- (void)updateNumberOf:(id)theObject forKey:(NSString *)key {
    NSNumber *oldNumber = [theObject valueForKey:key];
    NSNumber *newNumber = ...; // create new number
    [theObject setValue:newNumber forKey:key];
}

Called as [self updateNumberOf:theCoreDataObject forKey:@"number"];

like image 114
ughoavgfhw Avatar answered Oct 26 '22 17:10

ughoavgfhw