2

좋아,이 핵심 데이터에 대해 잘하고 있지만, 갈 방법이 있습니다. 내 뷰로드시 내 fetchedResultsController를 채우는 방법입니다.tableview 행 선택시 fetchedResultsController를 어떻게 업데이트 할 수 있습니까?

- (NSFetchedResultsController *)fetchedResultsController 
{ 
if (__fetchedResultsController != nil) 
{ 
    return __fetchedResultsController; 
} 

/* 
Set up the fetched results controller. 
*/ 
// Create the fetch request for the entity. 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
// Edit the entity name as appropriate. 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Visit" inManagedObjectContext:self.managedObjectContext]; 
[fetchRequest setEntity:entity]; 

// Set the batch size to a suitable number. 
[fetchRequest setFetchBatchSize:20]; 

// Edit the sort key as appropriate. 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; 
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:@"Queue"]; 
aFetchedResultsController.delegate = self; 
self.fetchedResultsController = aFetchedResultsController; 

NSPredicate *predicate =[NSPredicate predicateWithFormat:@"(isActive == YES)"]; 
[fetchedResultsController.fetchRequest setPredicate:predicate]; 

NSError *error = nil; 
if (![self.fetchedResultsController performFetch:&error]) 
{ 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

return __fetchedResultsController; 
} 

위대한 작품입니다. 내가 fetchedResultsController 내 tableView에 연결되어 있고 내가 표시되는 5 관리 개체가 있습니다. 내가 겪고있는 문제는 관리 대상 중 하나를 변경해야 할 때입니다.

술어에서 볼 수 있듯이 isActive == YES의 관리 대상 개체 만 필요하다고 지정하고 있습니다. 관리되는 객체의 isActive 상태를 NO로 변경 한 다음 fetchedResultsController에서 제거하고 궁극적으로 tableView에서 제거해야합니다.

-(void) seatedButton{ 
Visit * vis = [self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:reloadIndex inSection:0]]; 

vis.isActive = [NSNumber numberWithBool:NO]; 

NSError *error = nil; 

if (![self.managedObjectContext save:&error]) 
{ 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

[tableView reloadData]; 

} 

이 일 것으로 나타납니다,하지만하지 않습니다 : 여기에

내가 그렇게하려고 방법이다. tableView가 다시로드되면 5 개의 객체가 다시 4가되어야 할 때 술어의 요구 사항을 충족시키는 것으로 돌아옵니다!

내가 뭘 잘못하고 있니? fetchedResultsController를 업데이트하려면 어떻게해야합니까? 감사!

답변

1

자동으로이 작업을 수행해야하는 fetchedResultsController에 대한 대리 메서드가 있습니다. 당신이 컨텍스트를 저장하면, 그것은 당신을 위해 테이블을 업데이트, 그래서 당신은 전화를 할 필요가 없습니다 [tableView reloadData]

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller 
{ 
    [self.tableView beginUpdates]; 
} 

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type 
{ 
    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
     atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
     newIndexPath:(NSIndexPath *)newIndexPath 
{ 
    UITableView *tableView = self.tableView; 

    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeUpdate: 
      [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 

     case NSFetchedResultsChangeMove: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
{ 
    [self.tableView endUpdates]; 
} 

편집 :

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { 
    // configure cell; 
} 
:이 작업을 수행 할 경우, 다음과 같은 방법을 구현해야합니다
+0

답해 주셔서 감사합니다. 사실 configureCell (덕택에 Ray Wenderlich)를 포함하여 모든 위임 메서드를 구현했지만 실제로 셀을 제거하지는 않습니다. 이것은 나를 미치게합니다! – Lizza

+0

configureCell 메서드는 물론 tableView 데이터 소스 메서드가 모두 fetchedResultsController를 기반으로한다고 가정합니다. 당신이 모든 일을 올바르게하고있는 것처럼 보이기 때문에 그것이 여전히 업데이트되지 않는다면 나는 그것이 당신을 괴롭히는 이유가 무엇인지 상상할 수 있습니다. '[self.managedObjectContext save : & error]'를 호출하면 이에 따라 모든 것을 자동으로 업데이트해야한다. 내가 체크할만한 물건 : managedObjectContext가 null이 아니 었는지 확인하고 델리게이트 메소드에 로그가 있는지 확인하여 호출되는지 확인합니다. 또한, 이것의 아무 것도 배경 스레드에서 진행되고 있지 않습니까? 그렇다면 컨텍스트를 잃을 수 있습니다. – justin

0

[tableView reloadData]가있는 행이 문제를 해결하기 직전에 seatedButton 메소드에 다음 코드를 추가했지만 필요하다고 의사가 확신하지는 않습니다.

if (![self.fetchedResultsController performFetch:&error]) 
{ 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 
+0

귀하의 답변을 주셔서 감사합니다,하지만 그 많은 도움이되지 않았다 ... – Lizza

관련 문제