Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For instance, I subclassed UILabel and added a method or property called -verticalTextAlignment to align text vertically.
And in the future, if next version of SDK or iOS added a method or property which has the same name, then it is possible my app crashs or behaves unexpectedly.

*This problem happens even if you use category instead of subclassing.

Question1
How to avoid this kind of accidental overriding in Objective-C?
I think you can avoid this by prefixing all of your methods and properties like -XXX_verticalTextAlignment. But it is not realistic, is it?

Question2
I know that this kind of accidental overriding happens at compiling time or when you update your iOS SDK, OSX SDK, or XCode.

But is it possible to happen also when updating your iPhone's iOS version?
For example, is it possible that your app runs well on iOS5 but doesn't run on iOS6 due to accidental overriding in iOS6.(You can replace iOS5 and iOS6 with any versions, for example iOS5.0 and iOS5.1)

like image 356
js_ Avatar asked Aug 21 '12 06:08

js_


2 Answers

  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.

like image 64
trojanfoe Avatar answered Oct 27 '22 00:10

trojanfoe


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;
like image 20
Jessedc Avatar answered Oct 26 '22 23:10

Jessedc