如何避免Objective-C中的意外覆盖方法或属性 [英] How to avoid accidental overriding method or property in Objective-C

查看:83
本文介绍了如何避免Objective-C中的意外覆盖方法或属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我将 UILabel 子类化,并添加了一个名为 -verticalTextAlignment 的方法或属性来垂直对齐文本。< br>
在将来,如果下一版本的SDK或iOS添加了一个具有相同名称的方法或属性,那么我的应用程序可能会崩溃或意外行为。

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.

问题1

如何在Objective-C中避免这种意外覆盖?

我认为你可以通过为所有方法和属性添加前缀来避免这种情况,例如 -XXX_verticalTextAlignment 。但这是不现实的,是吗?

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?

问题2

我知道在编译时会发生这种意外覆盖时间或更新iOS SDK,OSX SDK或XCode时。



但是在更新iPhone的iOS版本时是否也有可能发生?

例如,您的应用程序是否可能在iOS5上运行良好但由于iOS6中的意外覆盖而无法在iOS6上运行。(您可以将iOS5和iOS6替换为任何版本,例如iOS5.0和iOS5.1) >

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)

推荐答案


  1. 是的你可以使用你自己的前缀,但这并不常见。

  1. Yes you could use your own prefix, however that is uncommon.

是的,它可能在O / S更新后发生; Objective-C是一种非常动态的语言,其中消息被发送到方法而不是被调用,就像在其他语言中一样。这些东西是在运行时计算出来的,而不是编译时间。

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.

这篇关于如何避免Objective-C中的意外覆盖方法或属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆