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

    Joined:
    Mar 27, 2009
    #1
    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:

    Code:
    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

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

    Joined:
    Mar 27, 2009
    #3
    Thank you!
     

Share This Page