What's wrong with using a category on NSObject to provide a default protocol implementation?

前端 未结 1 727
无人及你
无人及你 2021-01-17 23:08

I\'ve been looking for a way to use optional protocol methods and have clean code. In other words:
1: No respondsToSelector: calls all over my code
2.

相关标签:
1条回答
  • 2021-01-18 00:01

    Methods added to existing system classes should be prefixed somehow. I.e. exec_myMethod or exec_doSomethingToThis:. So, your solution is in violation of that.

    Beyond that, it also means that a class cannot opt out of whatever the default @optional method's behavior might be (which is basically nothing because your default implementation really should be a no-op).

    So, no, overall, there isn't something horrendously wrong with providing a default implementation beyond the violation of the should add prefix rule for adding methods via category to existing classes. But that isn't a hard rule.

    The other downside is that you are polluting the method namespace. This will be a disadvantage during development in that Xcode will code complete all the methods, easily avoided by simply not exposing the declarations (which don't need to be exposed). At runtime, it means that respondsToSelector: isn't useful for these methods, but that is kind of by design.

    Still... it smells to this old timer's code olfactory center.

    0 讨论(0)
提交回复
热议问题