문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top