Я начинаю запутываться. Я использую FetchedResultsController для своих данных таблицы. В каждой клетке У меня есть кнопка и текстовое поле маркированного с indexPath.Row в методе cellForRowAtIndexPath:iOS: Когда называется cellForRowAtIndexPath? Или теги обновляются?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Data model and cell setup
static NSString *CellIdentifier = @"MainCategoryCell";
MainCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
MainCategory *mainCategory = [self.fetchedResultsController objectAtIndexPath:indexPath];
/* ... */
cell.title.tag = indexPath.row;
cell.iconButton.tag = indexPath.row;
return cell;
}
Теперь мой метод ряда шага является немного более сложным для извлеченного контроллера результатов. Однако я уверен, что теги не обновляются после перемещения. Это нормально и метод cellForRow вызван только после создания новой ячейки? Нужно ли мне обновлять теги самостоятельно в методе перемещения? И как я могу получить доступ к свойствам тегов объектов внутри ячеек?
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath;
{
// Process the row move. This means updating the data model to correct the item indices.
//reordering has been defined in the CoreDataViewController so the
//FetchedResultsController doesn't mess up the reordering since he would update
//the fetched results permanently while reordering
self.reordering = YES;
//Makes only a mutable copy of the array, but NOT the objects (references) within
NSMutableArray *fetchedResults = [[self.fetchedResultsController fetchedObjects] mutableCopy];
// Grab the item we're moving
NSManagedObject *resultToMove = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];
// Remove the object we're moving from the array.
[fetchedResults removeObject:resultToMove];
// Now re-insert it at the destination.
[fetchedResults insertObject:resultToMove atIndex:[destinationIndexPath row]];
// All of the objects are now in their correct order. Update each
// object's displayOrder field by iterating through the array.
int i = 1;
for (MainCategory *fetchedResult in fetchedResults)
{
fetchedResult.position = [NSNumber numberWithInt:i++];
}
// Save
NSError *error = nil;
[self.budgetDatabase.managedObjectContext save:&error];
// re-do the fetch so that the underlying cache of objects will be sorted
// correctly
[self.fetchedResultsController performFetch:&error];
self.reordering = NO;
}
Не должен ли этот контролер результатов делать это автоматически ?! – MichiZH
Согласно документации Apple «Вместо этого вы должны вызвать функцию executeFetch: сбросить состояние контроллера, а затем перезагрузить данные в виде таблицы (reloadData)». Похоже, вам нужно перезагрузить данные после вызова функции executeFetch: в методе tableView: MoveRow: toIndexPath –
Не понимаю это из документации, но она работает. Можете ли вы объяснить это? Извините, я новичок во всем материале CoreData, и иногда я вижу, что FetchedResultsController запутывает ... как-то он контролирует и почему-то не делает этого ... – MichiZH