On 23/11/2009, at 8:32 AM, Ben Haller wrote:
> This same thing has been biting me. The problem is, I am guessing, that
> nothing in your code keeps a strong reference to your controller. Making a
> window with a controller creates an isolated group of objects that are not
> referenced from the outside, so they are collected when the collector gets
> around to it.
This is exactly correct. Unless there is something holding onto the window
controller, it will be eligible for collection as soon as scope leaves the
method that created it. What I usually do is create an ivar to hold onto the
window controller until such time as I want to manually release it:
@interface SomeClass : NSObject
{
ImagePanelController *ctrl;
}
@end
@implementation SomeClass
- (IBAction)newImagePanelForImage:(NSImage*)aImage
{
ctrl = [[ImagePanelController alloc] init];
[NSBundle loadNibNamed:@"ImagePanel" owner:ctrl];
[ctrl setImage:aImage];
}
@end
Note that in the original code the ImagePanelController instance was
autoreleased. This will do nothing when GC is enabled, but in this case would
ensure that the same problem occurs under non-GC mode, i.e. the controller will
be autoreleased as soon as the pool is drained.
Also, note that this is not the normal way for a NSWindowController to operate.
NSWindowController knows how to load a nib properly, so you should set up the
-init method of ImagePanelController like so:
@implementation ImagePanelController
- (id)init
{
self = [super initWithWindowNibName:@"ImagePanel"];
if(self)
{
//do some initialization
}
return self;
}
@end
That way, you can write the newImagePanelForImage: method like this:
- (IBAction)newImagePanelForImage:(NSImage*)aImage
{
ctrl = [[ImagePanelController alloc] init];
[ctrl setImage:aImage];
}
The window controller handles all the nib loading machinery itself.
--
Rob Keniger
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]