14

I am wondering which of the two following methods is the correct or preferred one to retrieve the superclass of a Class variable:

  1. Class getSuperclass(Class cls) { return [cls superclass]; }

  2. Class getSuperclass(Class cls) { return class_getSuperclass(cls); }

3 Answers 3

25

Well, the docs on class_getSuperclass() say this:

You should usually use NSObject‘s superclass method instead of this function

So, I'd go with door #1.

1
  • Because using this function should "#import <objc/runtime.h>" firstly. I'm kidding... Commented Oct 13, 2015 at 5:24
5

The accepted answer is technically correct (yes, that's what the docs say), and yet it's an incorrect answer.

[* superclass] only exists for objects that are subclasses of NSObject.

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.

1
  • Thanks for the valuable addition. In my case it worked as expected since I was only using it for specific classes which were derived from NSObject.
    – MKroehnert
    Commented Oct 12, 2012 at 21:58
2

I am positive they are absolutely identical, meaning that NSObject's superclass is implemented via class_getSuperclass. I am not sure, but I'd bet a beer on it.

3
  • 2
    I wouldn't bet against you, though I think a reasonable style guide for Obj-C is not calling the runtime's C interface if there's an equivalent object message.
    – Ben Zotto
    Commented Aug 21, 2011 at 22:24
  • Agreed, and I'd go with NSObject superclass, as well. But I think they are both "correct", as the OP requested. Commented Aug 21, 2011 at 22:32
  • Thanks for your comment Andrea. I checked the other answer because it also contains a link to the documentation where they suggest to call [NSObject superclass].
    – MKroehnert
    Commented Aug 22, 2011 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.