I have a container UIViewController which does the following when removing one of its children:
- (void)removeChildWithIndex:(NSUInteger)Index {
@autoreleasepool {
ChildViewController *child = [_children objectAtIndex:Index];
//Remove the child from the VC hierarchy
[child willMoveToParentViewController:nil];
[child.view removeFromSuperview];
[child removeFromParentViewController];
//Remove the child from array
[_children removeObjectAtIndex:Index];
}
//Post a notification for anyone who might care
[[NSNotificationCenter defaultCenter] postNotificationName:RemovedChildNotification object:self];
}
The root of my problem is that child is not being dealloced at the end of the @autoreleasepool block, but instead is released a little bit later (by the looks of it after the RunLoop has a chance to process an internal list of outstanding events):

This ordinarily wouldn't be a problem, but one object which is observing the NSNotification sent out at the end of the function above is relying on the child being dealloced before it receives the notification.
Can anybody explain/link me to some documentation to help me understand why child isn't released immediately?
Alternatively, if I have no choice about when child is dealloced, can anybody suggest a clean way of delaying my notification until after the dealloc? I suppose I could put a call in [ChildViewController dealloc] to inform the parent of its demise and fire off the notification at that point, but that's a pretty dirty way of doing it...
Try sending the notification in the next runloop iteration:
- (void)removeChildWithIndex:(NSUInteger)Index
{
ChildViewController *child = [_children objectAtIndex:Index];
//Remove the child from the VC hierarchy
[child willMoveToParentViewController:nil];
[child.view removeFromSuperview];
[child removeFromParentViewController];
[child didMoveToParentViewController:nil];
//Remove the child from array
[_children removeObjectAtIndex:Index];
//Post a notification for anyone who might care
[self performSelector:@selector(_postRemoveChildNotification) withObject:nil afterDelay:0.0f];
}
- (void)_postRemoveChildNotification
{
[[NSNotificationCenter defaultCenter] postNotificationName:RemovedChildNotification object:self];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With