Objective-C: override dynamic getter

I have a subclass of NSManagedObject MyClass with the myProp property, which is defined by @dynamic . There are various examples of reading myProp in my code through [myClass myProp] .

Now I want to define a getter (which returns myProp after adding something to it) for myProp without changing the various calls to [myClass myProp]. that is, without creating a getter that is called something other than getMyProp .

My question is: if I create a getter getMyProp that overrides the getter created by NSManagedObject , how can I access the original value that is stored in the database?

Thanks,

Akshay

+6
source share
1 answer

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)

+17
source

Source: https://habr.com/ru/post/897240/


All Articles