我在我的项目中使用CoreData。在我的项目中有一个TableViewCell和一个添加按钮。添加按钮单击并移动到另一个视图,并在一个文本字段中添加另一个视图。然后文本字段文本由CoreData在数据库中保存。然后在TableViewCell上正确获取值并重新加载。
我的问题是TableViewCell在一个按钮上。此按钮用于检查和取消选中单元格。我想按钮是选择并更新数据库上的值。我想要一个相同的实体值进行更新。并且更新相同的索引值。
假设单击按钮并设置正确的符号图像并将值保存在数据库相同的表和相同的值中。然后再次单击按钮并设置空白框图像。
现在按钮选择更改图像但不保存数据库中的值。
我只想更新和删除数据库中的按钮值。在同一个表和相同的索引中。
- (void)viewDidLoad {
[super viewDidLoad];
selectedButton = [[NSMutableArray alloc]init];//i've already defined the array at the .h file
for (int i = 0; i<90000; i++) //yourTableSize = how many rows u got
{
[selectedButton addObject:@"NO"];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(@"tableview cell");
All_Receipt_Cell *cell = [_table_view dequeueReusableCellWithIdentifier:@"htrcell"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[cell.date_lbl setText:[device valueForKey:@"date"]];
[cell.company_lbl setText:[device valueForKey:@"company"]];
[cell.total_lbl setText:[device valueForKey:@"total"]];
cell.currency_lbl.text = @"$";
UIImage *img = [UIImage imageNamed:@"images.jpeg"];
UIButton*toggleButton= cell.toggleButton;
[toggleButton setImage:img forState:UIControlStateNormal];
img = [UIImage imageNamed:@"images.png"];
[toggleButton setImage:img forState:UIControlStateSelected];
[toggleButton setTag:indexPath.row+100];//set the tag whichever way you wanted it, i set it this way so that the button will have tags that is corresponding with the table's indexpath.row
[toggleButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:toggleButton];
//and now we set the button's selected state, everytime the table reuse/redraw the cell the button will set it's selected state according to the array
if([[selectedButton objectAtIndex:indexPath.row]isEqualToString:@"NO"])
{
[toggleButton setSelected:NO];
}
else
{
[toggleButton setSelected:YES];
}
return cell;
}
-(void)buttonPressed:(UIButton*)sender
{
int x = sender.tag - 100; //get the table's row
if([sender isSelected] ) //if the button is selected, deselect it, and then replace the "YES" in the array with "NO"
{
[selectedButton replaceObjectAtIndex:x withObject:@"NO"];
[sender setSelected:NO];
NSLog(@"unselected");
}
else if (![sender isSelected]) //if the button is unselected, select it, and then replace the "NO" in the array with "YES"
{
[selectedButton replaceObjectAtIndex:x withObject:@"YES"];
[sender setSelected:YES];
NSLog(@"selected");
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Receipt_Details"];
Receipt_Detail *checkmark=[[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] lastObject];
[checkmark setValue:@"check" forKey:@"isDone"];
[self.managedObjectContext save:nil];
}
}