Alex Rivera | Logout

Converting self-releasing objects to ARC

Asked 2012-02-22T11:14:57.480
10

OK, so Apple brought ARC to us, which is great. After refactoring my Application to ARC almost everything works fine and it is a lot easier now to develop and maintain.

There is just one problem I still can't figure out.

My job management program shows different detail information of proposals, orders and so on in their own windows. So I have a special class where WindowControllers gets allocated and initiated with initWithWindowNibName and then the window is shown with showWindow:

DetailWindowController *proposalWindowController = [[DetailWindowController alloc] initWithWindowNibName:@"ThePorposalWindow"];
[proposalWindowController showWindow:nil];

Before ARC the Instance of the WindowController did the release like shown in the documentation:

- (void)windowWillClose:(NSNotification *)notification
{
   [self autorelease];
}

But now with ARC this is not possible anymore and what makes it even worse, in my special class where the WindowController is allocated and initiated, the same windowController is released by ARC because there is no pointer to the windowController.

My idea was to copy the windowController into an mutuable array:

[proposalWindowArray addObject:proposalWindowController];
[[proposalWindowArray lastObject] showWindow:nil];

And in the windowControllers delegate method windowWillClose I post a notification to my special class:

- (void)windowWillClose:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ProposalWindowWillClose" object:[[self window] windowController] userInfo:nil];
}

In my special class I listen to the notification and remove the object fro

Edit
Report

1 Answer

0

Without hacks, there is no elegant way to keep an object retained other than having a strong reference to it in some other object. For example, you could keep a static NSMutableArray/NSMutableSet, add your controller there, and remove it in windowsWillClose:. This will be shorter than posting a notification. To make this reusable, create a WindowControllerRegistry singleton with an array, where you add controllers like this one, and which will automatically listen to NSWindowWillCloseNotification and remove them from its array thus releasing ownership.

As a quick workaround, you could perform retain/autorelease calls from non-ARC file:

my_retain(self);
my_autorelease(self);

// ArcDisabled.mm
void my_retain(id obj) { [obj retain]; }
void my_autorelease(id obj) { [obj autorelease]; }
answered 2012-02-22T12:09:50.147

Your Answer