我必须在名为Person和Goal的核心数据中使用NSManagedObjects。他们有多对多的关系。我有一个表视图控制器,显示与给定的Person对象关联的Goal对象。这个tableview控制器的目的是允许你点击给定目标单元格内的“加号”按钮,并将“点”从Person对象转移到Goal对象。对核心数据对象的更改不会持续
取指令用于执行此请求是:
NSManagedObjectContext *context = self.context;
if (self.selectedItemID) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Goal"];
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES],
nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(self IN %@) AND (completed == %@)",
person.goals,
[NSNumber numberWithBool:NO]];
if (predicate) [request setPredicate:predicate];
//Note: |self.frc| is defined in the super class
self.frc = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:nil
cacheName:nil];
self.frc.delegate = self;
这是由 “加” 按钮,在各个目标小区调用的方法:
- (IBAction)modifyPointsForGoal:(UIButton *)sender {
//Get a reference to the |Goal| object for the button's cell. The view hierarchy may not be fixed,
//so traverse up the view hierarchy until a UITableViewCell is found and get its NSIndexPath
UIView *view = sender;
while (![view isKindOfClass:[GoalForPersonCell class]]) view = view.superview;
GoalForPersonCell *cell = (GoalForPersonCell *)view;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//Get reference to |Goal| and |Person| object
Goal *cellsGoal = (Goal *)[self.frc objectAtIndexPath:indexPath];
NSManagedObjectID *cellsGoalObjectID = cellsGoal.objectID;
Goal *goal = (Goal *)[self.context existingObjectWithID:cellsGoalObjectID
error:nil];
Person *person = self.person;
//Using the button tag numbers, increment/decrement values as needed
gFPVCSenderButtonType buttonType = (int)sender.tag;
switch (buttonType) {
case giveAdd:
[goal incrementValueBalanceWithDefaults];
break;
case giveSubtract:
[goal decrementValueBalanceWithDefaults];
break;
case bankAdd:
// decrementBalanceForGoalType returns FALSE if there are insufficient funds
if ([person decrementBalanceUsingGoal:goal])
[goal incrementValueBalanceWithDefaults];
break;
case bankSubtract:
// decrementValueBalance returns FALSE if there are insufficient funds
if ([goal decrementValueBalanceWithDefaults])
[person incrementBalanceUsingGoal:goal];
break;
default:
break;
}
}
的按钮在每个单元格中按预期工作 - 值从Person对象中获取并赋予由单元表示的Goal对象。我遇到的问题是对Person对象的更改写入持久性存储,但对Goal对象的更改不是。所以,当应用程序重新启动时,Goal对象看起来没有改变。
我已经使用SQL浏览器来验证更改没有写入磁盘。如果您在关闭应用程序之前查看其他VC中的目标对象,则目标对象的更改将可见 - 它就像Goal对象的更改被写入上下文一样,但它们不会持续存在,并且仅针对特定目的。
我尝试使用XCode重新生成NSManagedObject子类,但它没有解决问题。我完全被困住了,经过七个小时的试图弄清楚,我的智慧已经结束了。
显示请执行数据源委托方法。并请清楚解释您的问题。 –