【发布时间】:2014-03-21 21:52:28
【问题描述】:
所以我在 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;
}
我希望有人可以帮助我。谢谢:)
【问题讨论】:
标签: iphone uitableview checkmark