Question

What's the simplest way to check if a class method is implemented by a class?

For example, UIFont defines this method:

+ (UIFont *)preferredFontForTextStyle:(NSString *)style NS_AVAILABLE_IOS(7_0);

I cannot use instancesRespondToSelector: here, as preferredFontForTextStyle: is not an instance method but a class method.

I see class_getClassMethod, but… really? objc/runtime.h?

Was it helpful?

Solution

I'd use:

[MyClass respondsToSelector:mySelector]

All classes are instances of the base class. So all of NSObject's instance methods are also class methods for any class which derives from NSObject.

It makes some intuitive sense. Classes are objects, after all, so all of NSObject's methods make sense on classes.

If you're curious about why this happens in more detail, read up on metaclasses in Objective-C.

The reason that [[MyClass class] instancesRespondToSelector:mySelector] doesn't work is that NSObject actually defines +class to return self. Metaclasses are hidden from view by the frameworks and only accessible via the runtime API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top