Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom setter methods in Core-Data

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?

like image 986
Andrew Ebling Avatar asked Jun 04 '10 05:06

Andrew Ebling


People also ask

How do you annotate getter and setter with @API?

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.

How to use getters and setters in Kotlin?

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:

How do you write a getter and setter for a property?

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.

What is seed data in Entity Framework Core?

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.


1 Answers

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

like image 186
Dave DeLong Avatar answered Oct 08 '22 13:10

Dave DeLong