开发者

iPhone - how to declare a method and avoid leaks

开发者 https://www.devze.com 2023-01-19 04:50 出处:网络
Suppose I have a method like this - (UIButton *) createButtonAtX:(CGFloat)vX Y:(CGFloat)vY{ //... bla bla bla...

Suppose I have a method like this

- (UIButton *) createButtonAtX:(CGFloat)vX Y:(CGFloat)vY{

 //... bla bla bla... 
 //at some point I have

 UIButton *myButton = [[UIButton alloc] initWithFrame:myFrame];
 // we have an alloc here...

 // ... more bla bla and then
 return myButton;
}

as the button was allocated and not released this is technically a leak, right?

On my main code, the caller will be like

UIButton *oneButton = [self createButtonAtX:100 Y:100];
[myView addSubview:oneButton];
[oneButton release];

In 开发者_StackOverflowtheory, oneButton that is myButton on createButton method is being released on the main code, but even so, instruments will point the method as leaking...

how to solve that? using autorelease?

thanks


Replace the last line with

return [myButton autorelease];

The truth is a view retains a subview when you use -addSubview:.

0

精彩评论

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