我在 tabbarcontroller 的第二个选项卡上设置了以下代码。我第一次进入选项卡时,按预期正确获取了我的数据。但是,如果我离开选项卡并array
返回,则 fetch 请求返回的条目包含双倍条目。它返回的每个对象都是重复的。如果我离开选项卡并再次返回,则条目会再次重复,每个条目都给我 3 个。我的请求做错了什么会导致这种情况发生?
- (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];
}
更新:我切换到 NSFetchedResultsController 这解决了我的问题。