到目前为止,这是我的表格 View :单击 here
如您所见,我的 TableView 中有 4 个项目。我已经为它们加载了一个核心数据数组。在我的核心数据实体中,我有一个名为“付费”的属性设置为 bool 默认值“否”。我的表格 View 链接到一个 DetailViewController 页面,其中有一个名为“Paid”的按钮。当用户单击此按钮时,该特定项目将被标记为“PAID”。因此,在我的 cellForRowAtIndexPath 中,我检查该项目是否已付款。如图所示,我的代码在这里一定是错误的,因为只有一件商品被标记为已付款。但是,当我 NSLog TableView 中的其他项目时,它们也被标记为“付费”。这是我的 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];
}
}
最佳答案
从您的主 Controller 中获取选定对象的引用并将其放入您的行中:
NSManagedObject *YouOweData = [youOweArray objectAtIndex:0];
并将其替换为 ;
NSManagedObject *YouOweData = [youOweArray objectAtIndex:i];
要检查 mainController 中选定的行,您必须在 DetailViewController 中创建一个属性:
@property (nonatomic) int selectedIndex;
在 MainController 中,您必须在 didSelectRowAtIndexPath 中设置属性值。假设 detailController 是 DetailViewController 的对象。
设置 :
detailController.selectedIndex = indexPath.row;
详细 View Controller :
NSManagedObject *YouOweData = [youOweArray objectAtIndex:selectedIndex];
关于ios - 如何获取 TableView 中的特定单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663230/