I need to write a custom setter method for a field (we'll call it foo
) in my subclass of NSManagedObject
. foo
is defined in the data model and Xcode has autogenerated @property
and @dynamic
fields in the .h and .m files respectively.
If I write my setter like this:
- (void)setFoo: (NSObject *)inFoo { [super setFoo: inFoo]; [self updateStuff]; }
then I get a compiler warning on the call to super
.
Alternatively, if I do this:
- (void)setFoo: (NSObject *)inFoo { [super setValue: inFoo forKey: inFoo]; [self updateStuff]; }
then I end up in an infinite loop.
So what's the correct approach to write a custom setter for a subclass of NSManagedObject?
Annotate either the getter or the setter with @api, but not both. It’s a best practice to annotate the getter. To hold the property value inside the getter and setter, use a field. This example uses uppercaseItemName.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let’s define a property ‘ name ‘, in a class, ‘ Company ‘. The data type of ‘ name ‘ is String and we shall initialize it with some default value. The above code is equivalent to this code:
If you write a setter for a public property, you must also write a getter. Annotate either the getter or the setter with @api, but not both. It’s a best practice to annotate the getter. To hold the property value inside the getter and setter, use a field.
Model seed data. Unlike in EF6, in EF Core, seeding data can be associated with an entity type as part of the model configuration. Then EF Core migrations can automatically compute what insert, update or delete operations need to be applied when upgrading the database to a new version of the model.
According to the documentation, it'd be:
- (void) setFoo:(NSObject *)inFoo { [self willChangeValueForKey:@"foo"]; [self setPrimitiveValue:inFoo forKey:@"foo"]; [self didChangeValueForKey:@"foo"]; }
This is, of course, ignoring the fact that NSManagedObjects
only want NSNumbers
, NSDates
, NSDatas
, and NSStrings
as attributes.
However, this might not be the best approach. Since you want something to happen when the value of your foo
property changes, why not just observe it with Key Value Observing? In this case, it sounds like "KVO's the way to go".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With