Getting a particular superview in Objective-C

If you have, for example, a child view of a UITableViewCell and you need to get the UITableViewCell in question you can quickly do something like:

UITableViewCell *cell = (UITableViewCell *)the_view.superview.superview;    

It works but this code is fragile because it requires that the view heirarchy not change (also things like this usually point to a code organization issue but hey, i’m not here to judge). If we want to be able to add a scrollview in between without editing this method we’ll have to take a different approach.

// Add a category on UIView
-(UIView *)parents:(Class)class_name {
    UIView *s = self.superview;
    while (![s isKindOfClass:class_name]) {
        if (s.superview) {
            s = s.superview;
        } else {
            return nil;
    return s;

// Call the category on the_view and pass it the class that we're looking for.  It'll return the first superview that's that kind of class.
UITableViewCell *cell = (UITableViewCell *)[the_view parents:[UITableViewCell class]];

I named the category after jQuery’s parents method ( but call it what you want.

1 comment

  1. Good to see this — not because it’s hard to write (and I’m using Cocoa, anyway, so it’s slightly different), but because I can see that somebody else had this problem, and solved it in the same way that I would have.

    There are a million little things like this that are in Cocoa but I don’t think to look for, or I don’t know where to look for, or I don’t know what they’d be called. Seeing that somebody else had the same thought is a good suggestion that this isn’t in Cocoa, yet. 🙂

Leave a Comment