How do I check to see if one class is another's ancestor?

Discussion in 'iOS Programming' started by moonman239, Mar 20, 2014.

  1. moonman239 macrumors 68000

    Mar 27, 2009
    Example: I have a class named Animal. There are multiple subclasses of Animal, one of which is named Pet. There are four subclasses of Pet, named PetDog, PetCat, PetFish, and PetBird.

    I want my app to check whether an object is an instance of a subclass of Animal. I'm thinking of doing something like this:

    bool objectHasClassAsAncestor = false;
    Class class = [object class];
    while (([class superclass] != [Animal class]) & ([[object class] superclass] != [NSObject class])
    class = [class superclass];
    if ([class superclass] == [Animal class])
    objectHasClassAsAncestor = true;
  2. mjohnson1212 macrumors member

    Nov 15, 2007
    isKindOfClass on NSObject should work for what you want to do.
  3. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    Thank you!

Share This Page