4 ms·
Sometimes the simplest way is to use a "cool" language feature. For instance: say you have an app with 30 different ViewControllers, and you need them to respo
by bennyg 13y ago
Sometimes the simplest way is to use a "cool" language feature.
For instance: say you have an app with 30 different ViewControllers, and you need them to respond to the same notification. Sure, you could go back and refactor every one to subclass from another class that inherits from UIViewController - but then you need to make that for UITableViewControllers and UICollectionViewControllers, and potentially any other new view controllers that come along if your codebase ends up lasting for years.
Or, you could make one class category that method swizzles the viewDidAppear method to add the notification handling in immediately. Every class that inherits from UIViewController will now respond to that notification.
- babesh 13y agohttp://stackoverflow.com/questions/5272451/overriding-methods-using-categories-in-objective-c http://stackoverflow.com/questions/5272451/overriding-method...
- bennyg 13y agohttp://nshipster.com/method-swizzling/ http://nshipster.com/method-swizzling/
- babesh 13y agoWas addressing the use of categories to override not method swizzling per se. Oh, I read your link. So you add more behavior to it, not override it completely.
- seanmcdirmid 13y agoIsn't that just monkey patching?
- bennyg 13y agohttp://en.wikipedia.org/wiki/Monkey_patch http://en.wikipedia.org/wiki/Monkey_patch By that link's definition, then yeah, it's basically monkey patching.
- my3681 13y agoI think a lot could be said here for maintainability. As others have mentioned, it really goes a long way to take the time and refactor the class to inherit the extra/common functionality if you are working on a team or working on a project that you know will live a very long time. Swizzling will certainly work, but at what cost to readability, debugging and reuse? That's normally the question I ask before swizzling or doing fancy, dynamic things. Sometimes the quickest or even the most elegant solution isn't necessarily the "best" one. Best being a subjective term, I would say it depends on what you need from your code over time and with whom.