hvgotcodes
hvgotcodes

Reputation: 120268

iOs setPrimitiveValue

On an NSManagedObject, if I invoke setPrimitiveValue, does it need to be wrapped in {will|did}ChangeValueForKey statements, if it is used in a non-setting/getter method?

e.g. I want to have a method that takes a key (NSString) and increments the value of a property on the model object.

-(void) incrementItem:(NSString *)key
{
    NSNumber *value = [self primitiveValueForKey:key];
    int intValue = value.intValue;

    [self setPrimitiveValue:[NSNumber numberWithInt: intValue++] forKey:key];
}

Upvotes: 3

Views: 578

Answers (1)

Ash Furrow
Ash Furrow

Reputation: 12421

Calling your KVO methods when accessing the primitive value (or backing ivar for non-managed objects) should always be done. So, your method should look like:

-(void) incrementItem:(NSString *)key
{
    [self willAccessValueForKey:key];
    NSNumber *value = [self primitiveValueForKey:key];
    [self didAccessValueForKey:key];
    int intValue = value.intValue;

    [self willChangeValueForKey:key];
    [self setPrimitiveValue:[NSNumber numberWithInt: intValue++] forKey:key];
    [self didChangeValueForKey:key];
}

Upvotes: 1

Related Questions