这是我目前为止的表格视图:点击here
正如您所看到的,我的TableView中有4个项目。我已经加载了Core Data数组。在我的核心数据实体中,我有一个名为“付费”的属性设置为BOOLEAN默认值“NO”。我的表视图链接到一个DetailViewController页面,其中有一个名为“付费”的按钮。当用户单击此按钮时,该特定项目将标记为“PAID”。所以在我的cellForRowAtIndexPath中,我检查项目是否已付款。通过图片显示我的代码在这里一定是错的,因为只有一个项目被标记为付费。但是,当我在表格视图中NSLog其他项目时,它们也被标记为“付费”。这是我的cellForRowAtIndexPath方法的代码:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"OwedMoney"];
YouOweArray = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
OwedMoney *YouOweObject = [YouOweArray objectAtIndex:indexPath.row];
if (YouOweObject.paid.boolValue == NO)
{
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[cell setBackgroundColor:[UIColor redColor]];
}
else if (YouOweObject.paid.boolValue == YES)
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
[cell setBackgroundColor:[UIColor greenColor]];
}
在我的DetailViewController中,我有一个“付费”按钮,其中包含以下代码:
- (IBAction)paid:(id)sender {
//Fetch Entity
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"OwedMoney"];
//Create an array that stores the contents of that entity
youOweArray = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];
//Create managedObjectId
NSManagedObject *YouOweData = [youOweArray objectAtIndex:0];
NSManagedObjectID *moID = [YouOweData objectID];
//Successfully got the managedObjectId
NSLog(@"This is the id %@", moID);
BOOL Found = NO;
OwedMoney *Object;
for (OwedMoney *OwedObject in youOweArray)
{
NSManagedObjectID *OwedId = [OwedObject objectID];
NSLog(@"%@", OwedObject);
if (OwedId == moID)
{
Found = YES;
Object = OwedObject;
break;
}
}
if (Found)
{
BOOL isPaid = Found;
Object.paid = [NSNumber numberWithBool:isPaid];
NSLog(@"Is it paid: %@",Object.paid.boolValue? @"Yes":@"No");
NSError *error = nil;
[self.managedObjectContext save:&error];
}
}
答案 0 :(得分:0)
从主控制器中获取所选对象的参考,并将其放在您的行中:
NSManagedObject *YouOweData = [youOweArray objectAtIndex:0];
并将其替换为;
NSManagedObject *YouOweData = [youOweArray objectAtIndex:i];
要检查mainController中的选定行,您必须在DetailViewController中创建一个属性:
@property (nonatomic) int selectedIndex;
在MainController中,您必须在didSelectRowAtIndexPath中设置属性值。假设detailController是DetailViewController的对象。
设为:
detailController.selectedIndex = indexPath.row;
详细信息ViewController:
NSManagedObject *YouOweData = [youOweArray objectAtIndex:selectedIndex];