dimanche 25 octobre 2015

Encapsulating iOS logic

I am creating a UITextField that will format numbers. My initial thought was that I would subclass UITextField and the logic to format the numbers would be added to this subclass. My thinking is that this logic has nothing to do with my main ViewController and it should be encapsulated into the control itself.

So now I have a subclass. All I need to do now is listen for an event such as - (BOOL)textField: shouldChangeCharactersInRange: replacementString:.

However it seems that setting the delegate to self is not good design practice, which I have to say I was a little surprised. It makes complete sense to me to encapsulate the control logic in the subclass rather than a view controller or a completely separate class.

My current approach is to add a target action to the UITextField which listens for any changes - but this doesn't feel right. I want to use the delegate but it seems that's frowned upon.

So if delegate methods are only meant to be handed off to other objects, how are objects supposed to encapsulate logic related to those events, without using notifications or KVO or similar?

Why should the handling of events be handed off to say a ViewController when really it's the control that should handle that logic?

Aucun commentaire:

Enregistrer un commentaire