核心数据状态更改时,UISwitch不会打开

时间:2011-08-14 07:05:56

标签: iphone uitableview core-data uiswitch

我有一个表,其中每一行代表核心数据中的一个对象。每行包含一个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 setter,无论它们对开关状态的影响如何,都会阻止开关切换。

我只是在疏忽而且没有正确管理记忆吗?

- (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
    }
}

1 个答案:

答案 0 :(得分:4)

我认为代码应该是:

// Establish what position the switch should be in
    if([info.state isEqualToString:@"on"]){
        mySwitch.on = YES;
    } else {
        mySwitch.on = NO;
    }