【发布时间】:2014-01-05 22:29:05
【问题描述】:
好的,我对这个问题越来越笼统了,因为我注意到我的应用程序因此而出现了一些滞后。我注意到重新排序的问题,但它也发生在其他地方。我有一个 CoreDataViewController 类,它是我所有的表视图控制器的子类。在这个类中,我基本上拥有所有 NSFetchedResultsController 委托方法,就像它们在苹果文档中一样。
然后我试图找出这个 NSFetchedResultsController 注意到更改的频率,以找出我的时间滞后在哪里:
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if(self.suspendAutomaticTrackingOfChangesInManagedObjectContext) return;
NSLog(@"ControllerDidChangeContent");
TICK;
[self.tableView endUpdates];
TOCK;
}
例如在我的视图控制器 A 中,我有这个获取请求(从 viewDidLoad 调用):
- (void)setupFetchedResultsController
{
//NSError *error = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SpendingCategory"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]];
//[self.mainCategory.managedObjectContext executeFetchRequest:request error:&error];
request.predicate = [NSPredicate predicateWithFormat:@"belongsToMainCategory = %@", self.mainCategory];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.mainCategory.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
如果我在这个视图控制器中更改我的对象的属性,我的日志只会打印一次注释“ControllerDidChangeContent”。并且和预期的一样快。我的意思实际上只是一个简单的属性更改,只是更改一些数字或字符串等,例如:
spendingCategory.name = @"Hello world";
但是,如果我已经访问了另一个在 viewDidLoad 中设置其 NSFetchedResultsController 的视图控制器,我的日志将被打印两次。这是第二个 NSFetchedResultsController:
- (void)setupFetchedResultsController
{
self.managedObjectContext = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SpendingCategory"];
NSSortDescriptor *mainCatPosition = [[NSSortDescriptor alloc]
initWithKey:@"belongsToMainCategory.position" ascending:YES];
NSSortDescriptor *spendingCatPosition = [[NSSortDescriptor alloc]
initWithKey:@"position" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObjects:mainCatPosition,spendingCatPosition,nil];
request.predicate = [NSPredicate predicateWithFormat:@"liveBudget = %@", [NSNumber numberWithBool:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"belongsToMainCategory.position"
cacheName:@"LiveBudget"];
}
我之前提到的简单属性更改需要更长的时间。那是因为现在我的日志打印了两次(!)ControllerDidChangeContent。第一个 TICK-TOCK 仍然和以前一样快,但第二个超过一秒。我猜这是因为我有两个 NSFetchedResultsController 正在监视同一个实体。
问题: 我还是不太明白他们为什么会互相影响?我的意思是,我在一个视图控制器中更新了一个属性,所以另一个当然应该注意到这个变化,但是为什么触发了两个 didChangeContent 呢?
问题: 我怎样才能避免这种情况?或者我该如何改进?
【问题讨论】:
-
每个VC收到一个回调?或者收到重复的回调?表格视图单元格包含什么?您将委托设置在哪里?
-
每个 VC 在他们的视图中设置了 FRC 后都会收到两个回调。表格视图单元仅包含它们的所有属性(3 个 NSNumber,2 个字符串)。并且在视图中设置了委托也确实加载了
标签: ios objective-c core-data nsfetchedresultscontroller