Objective-C:检索 Class 实例的超类的首选方法
我想知道以下两种方法中哪一种是检索 Class
变量的超类的正确方法或首选方法:
Class getSuperclass(Class cls) { return [cls superclass]; }
Class getSuperclass(Class cls) { return class_getSuperclass(cls); } }
I am wondering which of the two following methods is the correct or preferred one to retrieve the superclass of a Class
variable:
Class getSuperclass(Class cls) { return [cls superclass]; }
Class getSuperclass(Class cls) { return class_getSuperclass(cls); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,文档关于
class_getSuperclass()< /代码> 说这个:
所以,我会选择 1 号门。
Well, the docs on
class_getSuperclass()
say this:So, I'd go with door #1.
接受的答案在技术上是正确的(是的,这就是文档所说的),但它是一个错误的答案。
是的,这是您日常使用的大部分课程。
然而...您可能会遇到许多类,它们不是 NSObject 子类。
简单的例子:如果您迭代“所有加载的类”(例如使用 objc_getClassList),那么如果您使用 [Class superclass] 方法,许多返回的类将使您的应用程序崩溃。
The accepted answer is technically correct (yes, that's what the docs say), and yet it's an incorrect answer.
Yes, that's most of the classes you use day to day.
However ... there are many classes you might encounter which are not NSObject subclasses.
Easy example: if you iterate over "all loaded classes" (e.g. using objc_getClassList), then many of the returned classes will crash your app if you use the [Class superclass] method.
我确信它们是完全相同的,这意味着
NSObject
的superclass
是通过class_getSuperclass
实现的。我不确定,但我敢打赌,一定要喝啤酒。I am positive they are absolutely identical, meaning that
NSObject
'ssuperclass
is implemented viaclass_getSuperclass
. I am not sure, but I'd bet a beer on it.