CoreDataとNSUserDefaultを使用したUITableViewのチェックマークには2つの問題があります
テーブルビューで新しいオブジェクトを作成すると、チェックが外れます。このオブジェクトをチェックすると、そのチェック。それで大丈夫です...しかし、10個のオブジェクトを作成して5番目のオブジェクトをチェックすると、それを削除してtableViewを更新すると、現在5番目のオブジェクトである6番目のオブジェクトもチェックされます。どうすればこれを修正できますか?
チェックされたオブジェクトを削除し、同じ名前のオブジェクトを作成すると、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;
}
誰かが私を助けてくれることを願っています。ありがとう :)