I try to get all subviews using this method but when i run the application, i have a message sent to deallocated instance error.
subviewsArray = self.view.subviews;
for (int i=0; i <subviewsArray.count; i++) {
UIView *subview = [subviewsArray objectAtIndex:i];
if (subview.tag >= 0) {
[subview removeFromSuperview];
}
}
And in my .h
@property (nonatomic, strong) NSArray *subviewsArray;
Change your loop code to this :
The Reason you are getting this issue is because, as your loop goes ahead from 0 to say 10th(assuming last) view, you start removing them from parent view, and so the count also changes and so the indexes of the remaining views.
In the end you end up trying to remove a view and send it a message removeFromSuperview, which is already deallocated, all because of change in the index.
better go reverse, last index to first.
I am surprised, why you didn’t get index out of bound exception.
not just here, in general whenever you traverse through a collection based on index and try removing elements, you will always face this issue.