【发布时间】:2011-10-26 16:46:05
【问题描述】:
我有一个表,其中每一行代表核心数据中的一个对象。每行都包含一个 UISwitch(修改为包含包含它的行的 indexPath),当切换它时应该切换核心数据中对象的 state 属性。
当前发生的情况是开关在被触摸时打开,然后又回到关闭状态!?
我的一个线索是当我注释掉时
// Establish what position the switch should be in
if([info.state isEqualToString:@"on"]){
mySwitch.selected = TRUE;
} else {
mySwitch.selected = FALSE;
}
和 changeState 方法中的两条 info.state 行,开关工作正常。似乎 info.state 设置器,无论它们对开关状态的影响如何,都会阻止开关切换。
我是不是太疏忽了,没有正确管理内存?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
InfoObject *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = info.name;
// Use a custom UISwitch that holds a pointer to the row it is associated with
NamedUISwitch *mySwitch = [[[NamedUISwitch alloc] initWithFrame:CGRectZero] autorelease];
mySwitch.indexPath = indexPath;
[mySwitch addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventValueChanged];
// And of course we need to know what the state is
NSLog(@"switchState:%@",info.state);
// Establish what position the switch should be in
if([info.state isEqualToString:@"on"]){
mySwitch.selected = TRUE;
} else {
mySwitch.selected = FALSE;
}
cell.accessoryView = mySwitch;
}
- (void) changeState:(id)sender {
InfoObject *info = [self.fetchedResultsController objectAtIndexPath:((NamedUISwitch*)sender).indexPath];
if(((NamedUISwitch*)sender).on){
info.state = @"on";
} else {
info.state = @"off";
}
NSError *error;
if (![self.context save:&error]) {
NSLog(@"Whoops, couldn't save state: %@", [error localizedDescription]);
//TODO: alertview
}
}
【问题讨论】:
标签: iphone uitableview core-data uiswitch