问题
Say you have a core data entity,
public class CDPerson: NSManagedObject
You get new info from the net ... a field changes,
p.name = 'Debbie'
That CDPerson
item is "touched" and hence,
your NSFetchedResultsController will trigger,
perfect.
But say CDPerson
can belong to CDAddress
In core data, a change in CDAddress
does not trigger a change in CDPerson
But. When an address is touched, you DO want to touch the relevant person items,
so that results controllers will know CDPerson
has been changed.
How to "touch" a cd entity?
One rubbish solution, assuming you have an unimportant field,
let touch = p.creationDate
p.creationDate = touch
Alternately you could add an Int64 and
p.touchyInt = a random number, or increment, etc
These are poor solutions
Is there actually a way to "touch" a core data entity, for results controllers?
This seems to be critical in propagating changes in related entities.
It's hard to believe there is no solution for this.
回答1:
Core Data recognizes changes by the firing of -willChangeValueForKey:
and -didChangeValueForKey:
as the comment from @pbasdf indicated. You can call only -didChangeValueForKey:
if you want but I would really do both.
Those calls also work on relationships. So in your Address object, you can touch both the value to be changed and the relationship to the person:
- (void)setCity:(NSString*)cityString
{
[self willChangeValueForKey:@"city"];
[self willChangeValueForKey:@"person"];
_city = cityString;
[self didChangeValueForKey:@"person"];
[self didChangeValueForKey:@"city"];
}
With an end result of the NSFetchedResultsController
being told that the associated person object has changed and the cell should be re-drawn.
来源:https://stackoverflow.com/questions/60277521/how-to-touch-a-core-data-entity-to-trigger-nsfetchedresultscontroller