Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: preferred way to retrieve the superclass of a Class instance

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); }

like image 838
MKroehnert Avatar asked Aug 21 '11 22:08

MKroehnert


3 Answers

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.

like image 164
Ben Zotto Avatar answered Nov 14 '22 13:11

Ben Zotto


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.

like image 35
Adam Avatar answered Nov 14 '22 13:11

Adam


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.

like image 38
Andrea Bergia Avatar answered Nov 14 '22 14:11

Andrea Bergia