Core Data object update when a property of its related object changes
I'm still getting used to how Core Data works and I've looked around for information about my problem but I haven't found any answers that obviously address my exact problem.
I have three classes of managed objects: loan, borrower, and photo. Borrower objects have a one-to-many relationship w开发者_如何学编程ith loan objects (meaning a borrower can have more than one loan but a loan can only have one borrower). Borrower objects also have a one-to-one relationship with a photo object.
I am using an NSFetchedResultsController to keep a table up to date with changes in a set of loan objects. When other borrower properties change the change notification reaches the NSFetchedResultsController and my table updates. But when the photo property changes to point to another photo object then no notification is passed to the NSFetchedResultsController. It seems that none of the loans that are related to the borrower are told when the borrower changes its photo relationship.
Please help!
You can try to handle the NSManagedObjectContextObjectsDidChangeNotification
notification.
It's a little squirrelly, but you could do the following, assuming that you have subclassed NSManagedObject for Loan, Borrower and Photo classes.
1.) In Loan, set up KVO for loan's photo's 'image' property.
2.) In Loan, add changeCount property (NSNumber*).
3.) When a loan is alerted to change in its photo's image, increment changeCount.
So, in very rough code, something like this:
in Load.m:
- (void) awakeFromFetch
{
[super awakeFromFetch];
[[self photo] addObserver:self
forKeyPath:@"image"
options:NSKeyValueObservingOptionNew
context:nil];
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"image"])
{
NSInteger temp = [[self changeCount] intValue];
++temp;
[self setChangeCount:[NSNumber numberWithInteger:temp]];
}
}
There are some caveats.
1) This only deals with 'fetch' and not with 'insert' (i.e., new loans).
2) This assumes that a fetched loan will have a photo.
3) This assumes that you have added 'changeCount' property to Loan.
4) I haven't tested this, though I use remotely similar mechanisms in one of my apps.
精彩评论