How to avoid accidental overriding method or property in Objective-C

前端 未结 4 1445
轮回少年
轮回少年 2021-01-04 05:47

For instance, I subclassed UILabel and added a method or property called -verticalTextAlignment to align text vertically.
And in the future, if

相关标签:
4条回答
  • 2021-01-04 06:16

    Prefixing your category methods are the safest way to avoid these conflicts in an every growing, non namespaced cocoa ecosystem.

    It's quite valid and reasonable that framework creators, open source developers and other individual developers should prefix their class methods.

    Quite often I write methods prefixed with my company initials, then continue with the method.

    - (void)JCMyMethodNamedSimilarToBaseClass;
    
    0 讨论(0)
  • 2021-01-04 06:27

    Question 1a Category

    Use a prefix, or avoid the whole mess and use functions instead.

    Question 1b Subclass Methods

    If a method does something general enough that the superclass may also implement it, I simply choose a method name which is a little more 'wordy' than Apple would conventionally choose -- such as specifying a non standard typename in the method's name. Of course, this only reduces the possibility of collision.

    If you need a higher level of security, you could just test this at execution (so you know when they are introduced) and hope every user stays up to date -- or you could rely on C and/or C++ more heavily (they do not have this problem).

    Question 2

    But is it possible to happen also when updating your iPhone's iOS version?

    Yes. It's not so unusual. When the frameworks are updated (e.g. via software update), they may contain updated frameworks. This code is loaded into the objc runtime, and you always get the version of the installed frameworks' objc implementations.

    It's also a much broader problem on OS X, where you may load code and/or plugins dynamically quite easily.

    0 讨论(0)
  • 2021-01-04 06:36

    An elegant solution is to check for the method being already there and only adding it if it isn't: Conditional categories in Mountain Lion

    0 讨论(0)
  • 2021-01-04 06:37
    1. Yes you could use your own prefix, however that is uncommon.

    2. Yes, it can happen after an O/S update; Objective-C is a very dynamic language where messages are sent to methods rather than being called, as in other languages. These things are worked-out at runtime, not compile time.

    Bottom line is yes, you might accidentally override a future base class method and the only solution is to be there when it happens and rename the method.

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