I'd like some assistance to properly remove subviews from a scrollview, to reduce memory usage. Every time the user scrolls, I ask to grab page, page -1 and page+1 to get the views loaded in the scrollview.
Now my issue is that if there's ten views side by side, when you reach the tenth view, all the previous 9 views are still subviews in the scrollview and in memory. I'd like to reverse load these views as well. Here's what I have so far:
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [self favouritesCount]) return;
// replace the placeholder if necessary
MyObject *myObj = (MyObj *)[fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:page inSection:0]];
MyView *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
controller = [[MyView alloc] initWithObject:myObj];
controller.delegate = self;
[viewControllers replaceObjectAtIndex:page withObject:controller];
}
// add the controller's view to the scroll view
if (nil == controller.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.frame = frame;
[scrollView addSubview:controller];
}
}
Now I have tried something like:
if (page > 2) {
[(UIView *)[[scrollView subviews] objectAtIndex:(page - 2)] removeFromSuperview];
}
But that just crashes it. It's probably a simple solution, so help is appreciated :)