I have following situation in my project (in which I use Core Data): I have an entity which has two BOOL properties: isCompleted and isNonVisit. It also has third property: NSNumber *status – the value of the property depends on both isCompleted and isNonVisit values.
When either of the BOOL property changes, I want status property to be actualised automatically.
All three properties must be present in underlying database, since I use fetchedResultsController that makes use of status property (as sort descriptor and as sectionNameKeyPath).
I came up with following solution:
in .h file:
@property (nonatomic, retain) NSNumber *isCompleted;
@property (nonatomic, retain) NSNumber *isNonVisit;
@property (nonatomic, retain) NSNumber *status;
- (NSNumber *)calculateStatus; //Returns proper status value based on isCompleted and nonVisit property values.
in .m file:
@dynamic isCompleted;
@dynamic isNonVisit;
@dynamic status;
- (void)setIsCompleted:(NSNumber *)newValue
{
[self willChangeValueForKey:@"isCompleted"];
[self setPrimitiveValue:newValue forKey:@"isCompleted"];
[self didChangeValueForKey:@"isCompleted"];
self.status = [self calculateStatus];
}
- (void)setIsNonVisit:(NSNumber *)newValue
{
[self willChangeValueForKey:@"isNonVisit"];
[self setPrimitiveValue:newValue forKey:@"isNonVisit"];
[self didChangeValueForKey:@"isNonVisit"];
self.status = [self calculateStatus];
}
The solution seems to work.
So, my question is: Is it OK? Am I violating some rules of CoreData or KVO?
Thanks for any suggestions.
Your method seems sound.
The only suggestion I would have is to reduce the redundancy by extracting the boolean information from the status with accessor methods rather than storing them. You still should be able to use the desired predicates for your fetch requests just using the status variable. But the overhead of storing this extra information should be minimal.