I have the following code set up on a second tab of a tabbarcontroller. The first time I come into the tab, my data is fetched properly, as expected. However, if I leave the tab, and come back, the array returned by the fetch request contains double the entries. Each object it returns is duplicated. If I leave the tab and come back again, then the entries get duplicated again, giving me 3 of each. What am I doing wrong with my request that would make this happen?
- (void)viewWillAppear:(BOOL)animated {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:delegate.managedObjectContext];
[fetchRequest setEntity:entity];
// sort the results, since we want the most recent entry first
NSSortDescriptor *dateSort = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateSort];
[fetchRequest setSortDescriptors:sortDescriptors];
NSError *error;
NSMutableArray *array = [[delegate.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
NSLog(@"error %@",[error localizedDescription]);
self.fetchedObjects = [array copy];
[array removeAllObjects];
[self.tableView reloadData];
}
Update: I switched to NSFetchedResultsController and this fixed my issue.
Switched to NSFetchedResultsController and it solved the problem.