What's a good way to remove all of the subviews of a UIScrollView?

Posted by Moshe on Stack Overflow See other posts from Stack Overflow or by Moshe
Published on 2010-11-28T03:29:49Z Indexed on 2011/01/01 6:54 UTC
Read the original article Hit count: 349

I have a scroll view and I need to reload the contents often while my app is running. Right now, I'm using the following line of code to remove the subviews before adding them back again:

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

Should I be using the following instead?

scrollView.subviews = nil;

For some reason, the (first) above line of code seems to crash the app every 16 times it is run. Am I leaking memory somewhere? The following method takes an array of views, the scroller (which is a constant) and the direction.

Edit:

- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
//Set up the scrollView

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

if([direction isEqualToString:@"horizontal"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
}else if([direction isEqualToString:@"vertical"]){
    scrollView.frame = CGRectMake(0, 0, 1024, 768);
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
}

for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {

    [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];

    if([direction isEqualToString:@"horizontal"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
    }else if([direction isEqualToString:@"vertical"]){
        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
    }

    [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
}

}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c