我有一个ManagedObject,我试图用NSFetchedResultsController监视它。我希望只有在修改或添加或删除对象本身时才会触发委托。当我修改对象关系中的任何对象时调用它的委托。以下是设置对象的代码和更新对象的代码。
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Set Enitity.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Workgroup" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController * aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
[aFetchedResultsController performFetch:nil];
以下是更新主对象和子对象的代码
dispatch_queue_t queue = dispatch_queue_create("com.background", NULL);
dispatch_async(queue, ^{
[[NSThread currentThread] setName:@"Workgroup"];
// Add x Workgroups
for(int a = 0;a < 10;a++)
{
Workgroup * workgroup = [[PCSDataStorage sharedInstance] workgroupWithID:[NSNumber numberWithInteger:a]];
[workgroup setName:[self genRandStringLength:10]];
// Add x Files
for(int b = 0;b < 1000;b++)
{
File * file = [workgroup fileWithID:[NSString stringWithFormat:@"%d",b]];
NSError * error;
if(![[PCSDataStorage sharedInstance] save:&error])
NSLog(@"Error:%@",error);
}
}
});
有一个更好的地方可以调用我在第一个循环结束时放置的保存方法,但性能非常差。