开发者

Memory management with a UIButton

开发者 https://www.devze.com 2023-03-25 15:12 出处:网络
I\'ve been having some issues with getting a good grasp on memory management. I\'m adding images and buttons to the main view using a loop. The开发者_运维百科 images release properly, but not the butt

I've been having some issues with getting a good grasp on memory management. I'm adding images and buttons to the main view using a loop. The开发者_运维百科 images release properly, but not the buttons.

My question boils down to, given the following code, why when i press the button to clear the screen, is the memory not release? The UIButton is autoreleased from UIButtonType custom, and setImage autoreleases transportation map.

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *homeButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [homeButton setFrame:[UIScreen mainScreen].bounds];
    [homeButton setBackgroundColor:[UIColor blueColor]];
    [homeButton setImage:[UIImage imageNamed:@"TransportationMap.png"] forState:UIControlStateNormal];
    homeButton.tag = 9399;
    [homeButton addTarget:self action:@selector(clearScreen) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:homeButton];
}

-(void)clearScreen 
{    
    for (UIView *view in [self.view subviews]) {
        [view removeFromSuperview];
    }
}


It looks to me like you are not allocating any memory in any of this code, so you should not need to release anything either.


You're placing concerned where you need not place them... Apple's rules of memory management state that anything you own (anything you alloced or copied or retained), you are responsible for releasing. Beyond that, you generally shouldn't care about what's going on. Apple could be caching images for its own purposes, etc... it is the OS's responsibility to deal with that, not yours. In your code, you are obeying all the rules (as far as I can tell)... you aren't allocing or retaining the button or the image. Therefore, you shouldn't be worried about releasing or freeing up that memory. Let the framework deal with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消