Iulian Onofrei
Iulian Onofrei

Reputation: 9720

Why is removing subviews from superview in Objective-C creating memory leaks?

I have a category for UIView which contains this method to remove all of its subviews:

- (void)empty {

    for (UIView *subview in self.subviews) {
        [subview removeFromSuperview];
    }
}

and upon profiling my project I see multiple memory leaks all pointing to this code:

[wrapperView empty];

which in turn calls the first method.

I searched on Google and found out a cleaner and better solution using:

[self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

which doesn't create memory leaks.

My question is, why is the old solution creating memory leaks? Aren't the UIView *subviews released at the end of the for loop?

Upvotes: 0

Views: 337

Answers (1)

Abizern
Abizern

Reputation: 150595

In the first method you are mutating the array while iterating through it, in the second you are just sending a message to each object in the array.

To see this for yourself, replace the first method with

NSArray *subviews = self.subviews.copy;
for (UIView *view in subviews) {
    [view removeFromSuperview];
}

This way you are working on a copy of the subviews array.

Upvotes: 1

Related Questions