我有一个表格列表,保存在具有bool值的核心数据中,当我选择一个单元格时,bool值在核心数据中保存为YES。但是当我选择一个以上的Cell时,2个单元格处于YES状态。我只想将1个单元格设置为是。我怎样才能做到这一点。 这是我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BestuhlungCell *cell =(BestuhlungCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.bestuhlungLabel.text = [managedObject valueForKey:@"bestuhlungstitel"];
NSData *data = [[NSData alloc] initWithData:[managedObject valueForKey:@"bestuhlungsfoto"]];
UIImage *image = [UIImage imageWithData:data];
cell.bestuhlungFoto.image = image;
cell.checkButton.hidden=YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [app managedObjectContext];
// BestuhlungCell *cell = (BestuhlungCell *)[tableView cellForRowAtIndexPath:indexPath];
Bestuhlung *bestuhlung=[self.fetchedResultsController objectAtIndexPath:indexPath];
if ([[bestuhlung valueForKey:@"check"] boolValue]) {
[bestuhlung setValue:[NSNumber numberWithBool:NO] forKey:@"check"];
} else {
[bestuhlung setValue:[NSNumber numberWithBool:YES] forKey:@"check"];
}
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
[self.navigationController popViewControllerAnimated:YES];
}
答案 0 :(得分:0)
从您的代码片段中可以清楚地看到,您只修改了所选单元格的值,但没有修改其他表值。
为了实现这一点,您已为表中的每一行设置BOOL值为NO,然后您可以继续使用相同的代码行。
答案 1 :(得分:0)
你可以做点什么:
NSArray *sections = self.fetchedResultsController.sections;
for(NSFetchedResultsSectionInfo *sectionInfo in sections) {
for(Bestuhlung *currentBestuhlung in sectionInfo.objects {
if(currentBestuhlung == bestuhlung) {
// the selected bestuhlung
if ([[bestuhlung valueForKey:@"check"] boolValue])
[bestuhlung setValue:[NSNumber numberWithBool:NO] forKey:@"check"];
else
[bestuhlung setValue:[NSNumber numberWithBool:YES] forKey:@"check"];
}
else {
// those are the other ones you want to uncheck
[currentBestuhlung setValue:[NSNumber numberWithBool:NO] forKey:@"check"];
}
}
}