Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure as property for UITableViewCell subclass to update value : Is it a bad idea? [closed]

I would like some opinions on a idea I just had :

I have a bunch of UITableViewCell subclass. In my particular case it's just to add a UISwitch and have a property to access it.

Setting the switch's value is straight forward. Updating the Bool associated to this switch not so much.

I thought of adding a closure as a property of my cell so that I can just call it to update my bool in my UITableViewController subclass

Here is some the code I thought of :

class SwitchTableViewCell:UITableViewCell {
    @IBOutlet var theSwitch:UISwitch!

    var switchValueChangedBlock:((Bool) -> Void)?

    override func awakeFromNib() {
        theSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: .ValueChanged)
    }

    deinit {
        theSwitch.removeTarget(self, action: nil, forControlEvents: .AllEvents)
    }

    func setCallback(callback:(Bool) -> Void) {
        switchValueChangedBlock = callback
    }

    func switchValueChanged() {
        switchValueChangedBlock?(theSwitch.on)
    }
}


class myTableViewController:UITableViewController {
    var alarmEnabled:Bool = true
 ...
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell?
        if indexPath.section == enableSection {
            cell = tableView.dequeueReusableCellWithIdentifier(enableAlarmCellIdentifier,forIndexPath: indexPath)
            let myCell = cell as! SwitchTableViewCell
            myCell.theSwitch.on = alarmEnabled
            myCell.setCallback({[unowned self] (boolValue:Bool) in
                self.alarmEnabled = boolValue
            })
        }
    }

...
} 

As advantages I see following :

  • No need of delegate
  • No method called where I need to determine which value I need to update (I have multiple instances of my cell for different variables)

I can't grasp the possible drawbacks my idea could have and if in overall it's a bad or a good idea.

like image 606
Matthieu Riegler Avatar asked Nov 19 '15 16:11

Matthieu Riegler


1 Answers

Personally I am kinda old school and simply prefer the delegation pattern over closures.

But for your question ... what you suggest is exactly what closures are made for. Just go for it.

You simply hand over to another class' object some piece of code (or the reference to some subroutine's entry point respectively) that you want to be executed when some event occours. That's what it's made for and that's what you are doing.

like image 135
Hermann Klecker Avatar answered Oct 04 '22 19:10

Hermann Klecker