【问题标题】:UISwitch won't turn on when core data state is changed核心数据状态改变时UISwitch不会开启
【发布时间】: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


    【解决方案1】:

    我认为代码应该是:

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

    【讨论】:

    • 效果很好。 UISwitch 上的所有属性都让我感到困惑!在 changeState 方法中,我使用了 on 属性,但之前忘记更改它。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2021-10-22
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多