tags:

views:

32

answers:

1

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 theory, 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

+4  A: 

Replace the last line with

return [myButton autorelease];

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

Costique
Apple's Memory Management Programming Guide has a good explanation of what's going on here. http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043-SW5
Robot K
but how do I do that when I use a quartz function like CGImageMaskCreate, that needs to be released using CGImageRelease. I cannot simply put it as autorelease, or can I? Suppose I use something like... CGImageRef mask = CGImageMaskCreate(... and at the end a return mask; what can I do if I need to return a CGImageRef?
Digital Robot
In fact, you can for any Core Foundation object. There is no magic in autorelease, it just means the release message is sent by an NSAutoreleasePool. In your example you would return [(id)mask autorelease].
Costique
thanks... [(id)mask autorelease]??? why not just [mask autorelease]? ... sorry bothering you, but I need to understand this :)
Digital Robot
Semantically, CGImageRef is not an Obj-C object which responds to autorelease. Casting is needed only to please the compiler. It does not know anything about toll-free bridging, so from the C standpoint CFTypeRef and id are pointers to different structs. If you can live with a warning, you may omit the cast.
Costique