3

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.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Kyle
  • 1,662
  • 2
  • 21
  • 38

3 Answers3

6

You can use indexOfObjectWithOptions:passingTest: method to search the array in reverse for an object that passes a test using a block, and then delete the object at the resulting position:

NSUInteger pos = [myArray indexOfObjectWithOptions:NSEnumerationReverse
                          passingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    return [obj isKindOfClass:[UIImageView class]]; // <<== EDIT (Thanks, Nick Lockwood!)
}];
if (pos != NSNotFound) {
    [myArray removeObjectAtIndex:pos];
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
3

How about:

UIWindow *window = [[UIApplication sharedApplication] window];
UIView *imageView = nil;
for (UIView *view in window.subviews)
{
    if ([view isKindOfClass:[UIImageView class]])
    {
        imageView = view;
    }
}

//this will be the last imageView we found
[imageView removeFromSuperview];
Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103