3

I need to call a class method on a variable of type Class, which I know holds a subclass of a base class, MyBaseClass...

- (void)foo:(Class)clazz {
  // Now i want to call +myClassMethod on clazz
}

I don't know if this is actually possible. If it is, is there a safer way to guarantee that clazz is actually a subclass of MyBaseClass?

Thanks in advance

2 Answers 2

6

You can use -respondsToSelector:, just like you would with any Objective-C object. You can also use +isSubclassOfClass: to test whether the class is a subclass of another class.

- (void)foo:(Class)clazz 
{
    if ([clazz respondsToSelector:@selector(myClassMethod)])
    {
        [clazz myClassMethod];
    }
    else
    {
        // clazz does not implement that class method.
    }

    if ([clazz isSubclassOfClass:[MyBaseClass class]])
    {
        [clazz myClassMethod];
    }
    else
    {
        // clazz is not a subclass of MyBaseClass.
    }
}
1
  • There is a "not" missing in the first comment. I would edit it in, but edits have to be at least 6 characters and I don't want to change anything else in your answer.
    – Kaiserludi
    Oct 28, 2013 at 21:13
1

Try this:

if ( [clazz isKindOfClass:[MyBaseClass class]] ) {
  [clazz myClassMethod];
}
3
  • [clazz isKindOfClass:[MyBaseClass class]] returns false here, since it's a Class itself, not an instance of one. [clazz myClassMethod] DOES work. Thanks! Looks like [clazz respondsToSelector:@selector(myClassMethod)] does the job. firstStackOverflowExperience.setSuccessful(true); Dec 12, 2011 at 1:41
  • My mistake. Darren's suggestion of isSubclassOfClass or respondsToSelector should work in its place.
    – jverdi
    Dec 12, 2011 at 1:45
  • 1
    -isKindOfClass: is an instance method, and would return NO in this case because clazz is not an instance of MyBaseClass. Use + isSubclassOfClass: instead on class objects. These are all declared in NSObject.h.
    – Darren
    Dec 12, 2011 at 1:47

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.