我应该在addTarget之前删除目标

Bot*_*Bot 7 objective-c ios5

UIControl - 更改分配的选择器:addTarget&removeTarget

您应该在更改为另一个目标之前删除目标的状态.但是如果我在cellForRowAtIndexPath中设置目标呢?我是否应该在再次添加目标之前删除它,即使它没有改变?如果我不删除它或它只是覆盖它,它会调用该方法两次吗?

[cell.cellSwitch removeTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged];
[cell.cellSwitch addTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged];
Run Code Online (Sandbox Code Playgroud)

Joo*_*ong 0

根据我的经验,它只会被调用一次。

但在我看来,最好 removeTarget始终使用,因为代码将来可能会更改。有一天,您可能需要添加多个目标和选择器。

成为安全、可扩展且可维护的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = // code with reuse identifier ...
    if(cell == nil)
    {
        // making view for cell ....
    }

    // myAction will be called ONLY ONCE after many times of scrolling
    [cell.myButton addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside]; 

    return cell;
}
Run Code Online (Sandbox Code Playgroud)