所以我在 UITableView 中使用 CoreData 和 NSUserDefault 的复选标记有两个问题
如果我在 tableview 中创建一个新对象,它是未选中的。当我检查这个对象时,它的检查。所以没关系...但是当我创建 10 个对象并检查第 5 个对象时,删除它并刷新 tableView,而不是第 6 个对象,现在是第 5 个对象,也被选中。我怎样才能解决这个问题?
当我删除一个已检查的对象并创建一个具有相同名称的对象时,刷新 UITableView,它会在创建后被检查吗?什么?:D
我猜 NSUserDefault 是问题所在,但我不知道......
所以这是我的代码:
复选标记:
- (BOOL) getCheckedForIndex:(int)index
{
if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES)
{
return YES;
}
else
{
return NO;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//Use checkedCellAtIndex for check or uncheck cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self checkedCellAtIndex:indexPath.row];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
表视图:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"cell_background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[ [UIImage imageNamed:@"cell_background.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
// Configure the cell...
NSManagedObject *device = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{device = [searchResults objectAtIndex:indexPath.row];}
else
{device = [self.cart objectAtIndex:indexPath.row]; }
[cell.textLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"cartProductName"]]];
cell.tintColor = [UIColor orangeColor];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
我希望有一个人可以帮助我。谢谢 :)