Kyle
Kyle

Reputation: 1672

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.

Upvotes: 3

Views: 1594

Answers (3)

vikingosegundo
vikingosegundo

Reputation: 52227

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.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

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];
}

Upvotes: 6

Nick Lockwood
Nick Lockwood

Reputation: 40995

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];

Upvotes: 3

Related Questions