Reputation: 9720
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 *subview
s released at the end of the for
loop?
Upvotes: 0
Views: 337
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