我有这个与更新我的 NSManagedObject 相关的奇怪问题。当我尝试更新其属性之一时,它会在 UITableview 中消失,并且只有在我从核心数据重新获取时才会再次消失。我认为这是由我如何在另一个线程中获取我的实体的内容引起的,如下所示:
[[[DataManager sharedInstance] backgroundManagedObjectContext] performBlock:^{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"Ret" inManagedObjectContext:[[DataManager sharedInstance] backgroundManagedObjectContext]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"menu.name == %@ ", self.menu.name];
fetchRequest.resultType = NSManagedObjectIDResultType;
NSArray *results = [[[DataManager sharedInstance] backgroundManagedObjectContext] executeFetchRequest:fetchRequest error:nil];
NSLog(@"%@", [NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
[self loadWithObjectIDs:results];
[_theTableview reloadData];
});
}];
这是在 viewDidAppear 方法中触发的。
然后我的 NSFetchResultsController 方法在主线程上更新 UI:
-(void)loadWithObjectIDs:(NSArray *)objectsIDs {
_theManagedObjectContext = [[DataManager sharedInstance] mainManagedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = [NSEntityDescription entityForName:@"Ret" inManagedObjectContext:_theManagedObjectContext];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"SELF IN %@ ", objectsIDs];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
fetchRequest.sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[NSFetchedResultsController deleteCacheWithName:@"dishes"];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_theManagedObjectContext sectionNameKeyPath:nil cacheName:@"dishes"];
_fetchedResultsController.delegate = self;
NSError *error = nil;
if (![_fetchedResultsController performFetch:&error]) {
NSLog(@"Fetch Failed");
}
NSArray *contentsOfFetch = _fetchedResultsController.fetchedObjects;
}
然后在另一个连接到我的 UITableViewCell 中的按钮的方法中,我更新了我的 NSMangedObject 的属性:
-(void)addTC:(UIButton *)sender {
//sender.tag equals indexPath.row
NSIndexPath *ip = [NSIndexPath indexPathForRow:sender.tag inSection:0];
Ret *ret = (Ret*)[_fetchedResultsController objectAtIndexPath:ip];
//The Cell disappears if I use this code to update my attribute.
NSInteger amountToUpdate = ret.amount.intValue;
amountToUpdate++;
ret.amount = [NSNumber numberWithInt:amount];
/*Method to Save Main Context: includes:
NSError *error = nil;
if (![context save:&error]) {
}*/
[self saveCurrentContext:_theManagedObjectContext];
}
当我更新其属性时,我将如何解决这个小问题,以便 NSManagedObject 在我的 UITableview 中不会消失?