Search code examples
objective-cioscocoa-touchnsarraysubviews

NSArray remove last object of type?


Working with an array of UIViews and UIImageViews ([[[UIApplication sharedApplication] window] subviews]). I need to remove only the object of the highest index of the UIImageView type.


Solution

  • another block-based solution

    [window.subviews enumerateObjectsWithOptions:NSEnumerationReverse 
                                      usingBlock:^(id view, NSUInteger idx, BOOL *stop) 
        {
            if ([view isKindOfClass:[UIImageView class]]){
                [view removeFromSuperview];
                *stop=YES;
        }
    }];
    

    non-block solution:

    for (UIView *view in [window.subview reverseObjectEnumerator])
    {
        if ([view isKindOfClass:[UIImageView class]]){
                [view removeFromSuperview];
                break;
        }
    }
    

    I published some demo code, that shows both solutions.