Reputation: 3943
I have a question about NSFetchedResultController updating problem.
As you may have already known, if I fetch all items and set the NSFetchedResultController's delegate, then if the data has been changed, the controller will catch the changes and auto update its objects.
But if I fetch items with NSPredicate, it does not catch any change nor its objects. Can someone tell me why?
Here is the codes with NSPredicate set.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.globalContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:200];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Department" ascending:YES selector:nil];
NSArray *descriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:descriptors];
[sortDescriptor release];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"Department IN %@",departmentArray];
[fetchRequest setPredicate:pred];
self.resultsController = [[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.globalContext sectionNameKeyPath:@"Department" cacheName:@"Root"] autorelease];
self.resultsController.delegate = self;
[self.resultsController performFetch:nil];
[fetchRequest release];
In the code, I set the @"Department" as the sectionNameKeyPath, and I only need "Person" items from a number of Department (departmentArray), not all Departments.
If I remove the NSPredicate from the NSFetchRequest, then each time a person item with even a new department is inserted, the resultsController will know and trigger the delegate.
But If I keep the NSPredicate, the resultsController won't be able to know any change. For example:
My department array has the following names: @"Sales", @"Human Resources".
Initially, there is no persons from @"Sales" in the Core Data. I do a fetch,then only persons from @"Human Resources" are obtained.
Then a person from @"Sales" is inserted, I think the resultsController should automatically update, right? Because the new person with @"Sales" fits to the NSPredicate, right?
Thanks
Upvotes: 0
Views: 346
Reputation: 64428
The predicate is not dynamic and does not respond to changes in the departmentArray
after the predicate has been created. As far as the predicate is concerned, departmentArray
only ever contains Human Resources
. Further, the fetch request is likewise static and does not change so even if the predicate did change, the fetch request would not.
If you change the departmentArray
, you need to generate a new fetch request for the fetched results controller.
Upvotes: 1