2012-04-23 11 views
6

UIControl - changing assigned selectors: addTarget & removeTargetDevo removeTarget prima addTarget

membri che è necessario rimuovere l'obiettivo prima cambiare ad un altro. Tuttavia, cosa succede se sto impostando il target in cellForRowAtIndexPath? Devo rimuovere il target prima di aggiungerlo di nuovo anche se non cambia? Chiamerà il metodo due volte se non lo rimuoverò o lo sovrascriverà?

[cell.cellSwitch removeTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged]; 
[cell.cellSwitch addTarget:self action:@selector(notifySwitchChanged:) forControlEvents:UIControlEventValueChanged]; 

risposta

0

In seguito alla mia esperienza, verrà chiamato solo una volta.

Ma IMO, è meglio utilizzareremoveTarget sempre perché il codice può essere modificato in futuro. E un giorno potrebbe essere necessario aggiungere più target e selettori.

Essere un codice sicuro, scalabile e mantenibile.

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

Invece di aggiungere/rimuovere gli obiettivi, ho scoperto che se sto già sottoclasse il UITableViewCell, aggiungerò un nuovo delegato e impostare il delegato al controller della vista. In questo modo, tutti i metodi richiamati dal delegato possono passare nell'intera cella e pertanto è possibile ottenere il percorso dell'indice della cella chiamando il metodo indexPathForCell di UITableView.

Problemi correlati