简体   繁体   中英

when are objects released

I believe I have to release an object if I created it with the keywords init, alloc, copy, or move I believe. I may create objects with code that don't use this keywords so I guess I don't have to release them right? so take for instance this code:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Hello" forState:UIControlStateNormal];
button.frame = CGRectMake(40.0, 200.0, 170.0, 40.0);
[self.view addSubview:button];

since I did not use any of those keywords in my code I should not release it right? so when is that object being released? I am little confused with the memory managment stuff.

The only object you created here is the UIButton, and you used the buttonWithType class method. That is returning you autoreleased object, so you don't have to release it.

Keep in mind though that if you were to need this button at a later time you would need to retain it and eventually release it. Because you add this button to a view, the view retains a copy in this case so again you don't need to worry about it.

If you're running XCode 4 I recommend running the 'analyze' mode to run quick basic check for memory leaks... that looks fine (your code).

You are absolutely correct in that you don't have to explicitly release anything that you don't take ownership of via alloc, copy, new, or retain.

In this case, you've created the button via a convenience method (buttonWithType:). This returns an autoreleased UIButton object. This is released automatically when the autorelease pool is flushed at the end of the run loop.

There's nothing for you to worry about here. Let the runtime take care of it.

There is an NSAutoreleasePool that manages the memory for you. You were correct about alloc and copy (alloc and init are usually together) but not move. Another one that returns a retained object is methods prefixed with new ex. +(id)new; . An auto release pool is required for each thread to manage memory for each event loop.

An example of how a button implementation may look

-(id)buttonWithType:(UIButtonType)type
{
    UIButton *button = [[[UIButton alloc] initSecretlyWithType:type] autorelease]; 
    //Customize button if needed
    return button;
}

See Using Autorelease Pools for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM