Search code examples
ios6uiviewautomatic-ref-counting

Should you remove all subviews when using ARC


I'm stacking UIViews on top of each other as the user moves through the application, going backwards and forwards between different screens. These UIView can be normal controls (buttons, labels, etc) as well as custom controls inherited from UIView. When pressing the back button on one of the screens I do a lot of cleanup code to free the memory of my instance variables, as well as stopping timers and closing network connections. I think it is also important to here that I am using ARC and deploy to iOS 6 and iOS 7 devices.

A typical control will be coded like this :

    UIImageView *ivSoundBottom = [[UIImageView alloc] initWithFrame:CGRectMake(270, 365, 30, 30)];
    UIImage *imgSoundBottom = [UIImage findCustomImage:@"ICN_Alarm_Sound_Bottom.png"];
    [ivSoundBottom setImage:imgSoundBottom];
    [self addSubview:ivSoundBottom];
    imgSoundBottom = nil;
    ivSoundBottom = nil;

This control is created when the screen loads and is never referenced again.

My question is : Under ARC, do I still need to iterate through all subviews and call removeFromSuperview on each of them to dealloc the memory?


Solution

  • No, you don't. You also don't need these statements:

    imgSoundBottom = nil;
    ivSoundBottom = nil;
    

    As ARC will realize the references to those variables has gone out of scope and do that for you.