好的,我越來越多地瞭解這個問題,因爲我注意到由於這個原因我的應用程序出現了一些滯後現象。我注意到重新排序的問題,但它也發生在其他地方。我有一個CoreDataViewController類,所有我的表視圖控制器的子類。在這個類中,我基本上擁有所有NSFetchedResultsController委託方法,就像它們在Apple文檔中一樣。NSFetchedResultsControllers在不同的視圖控制器互相更新?
然後我試圖找出變化是如何經常被這個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";
然而,如果我已經訪問其設置的NSFetchedResultsController以及在viewDidLoad中另一個視圖控制器,我的日誌打印出來兩次。這裏是第二個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收到一個回調?或者一個接收重複的回調?表格視圖單元格包含什麼內容?你在哪裏設置代表? – Wain
每個VC在其視圖加載完成後都設置了FRC後會收到兩個回調。表視圖單元格包含所有屬性(3個NSNumbers,2個字符串)。並且代表被設置在視圖中也加載了 – MichiZH