Padin215
Padin215

Reputation: 7484

NSManagedObject Class and creating a Setter method

So in a regular Class, you can override the setter method for a class property:

-(void)setSortBy:(NSString *)sortBy {
    // Do other stuff

    _sortBy = sortBy;
}

using the _ prevents an infinite loop of the method calling its self.

I am trying to do something similar with a NSManagedObject class, but it does not give the option to use the underscore (_):

-(void)setHasNewData:(NSNumber *)hasNewData {
    // update self.modifiyDate

    _hasNewData = hasNewData;
}

Gives me an error and suggests I replace _hasNewData to hasNewData.

Is this how it should be done or will it give me an infinite loop?

I want it to update the NSManagedObject's property modifyDate anytime I set hasNewData.

Upvotes: 3

Views: 468

Answers (1)

Martin R
Martin R

Reputation: 539815

Your first example for a "regular class" works if _sortBy is the instance variable backing up the sortBy property (e.g. the default synthesized instance variable for that property).

But Core Data properties are not backed up by instance variables. When overriding Core Data accessors, you have to use the "primitive accessors", and also trigger the Key-Value Observing notifications:

-(void)setHasNewData:(NSNumber *)hasNewData {
    [self willChangeValueForKey:@"hasNewData"];
    [self setPrimitiveValue:hasNewData forKey:@"hasNewData"];
    [self didChangeValueForKey:@"hasNewData"];

    // do other things, e.g.
    self.modifyDate = ...;
}

More examples can be found in the "Core Data Programming Guide".

Upvotes: 7

Related Questions