To access the base values ββof a managed entity, you use the following two methods:
- (id) primitiveValueForKey: (NSString *) key
- (void) setPrimitiveValue: (id) value for keyKey: (NSString *)
This is often used to convert NSNumber attributes to their βrealβ type, for example, the bool property:
- (BOOL)isShared { [self willAccessValueForKey:@"isShared"]; NSNumber *underlyingValue = [self primitiveValueForKey:@"isShared"]; [self didAccessValueForKey:@"isShared"]; return [underlyingValue boolValue]; }
willAccessValueForKey: and didAccessValueForKey: are required by the base class of managed objects to handle errors and relationships, etc.
And if you ended up writing a setter, you should also wrap the accessor in KVC methods:
- (void)setShared:(BOOL)isShared { NSNumber *newUnderlyingValue = [NSNumber numberWithBool:isShared]; [self willChangeValueForKey:@"isShared"]; [self setPrimitiveValue:newUnderlyingValue forKey:@"isShared"]; [self didChangeValueForKey:@"isShared"]; }
Having said that, I personally do not recommend that you keep the same method name unless you have a good reason. For derived values, you usually want to create a completely new method with a different name. It does not take long to quickly find / replace all your code.
EDIT: added willAccessValueForKey: / didAccessValueForKey: (thanks jrturton)
source share