简体   繁体   中英

Having object send its own delegate a message after its been removed from superview

I have the following method:

- (void) okButtonPushed
{
    if ([self.delegate respondsToSelector:@selector(alertViewWillDismiss:)])
    {
        [self.delegate alertViewWillDismiss:self];
    }

    [self removeFromSuperview];
}

It's an OK button on a custom AlertView object that when pushed dismisses the alert. I'd like for the delegate to send a message AFTER the alert has been removed from the superview, but obviously this isn't possible since it will be deallocated by then. The only other solution I can think of this is for the superview to keep another pointer to my object, but then everytime I do an alert, I have to implicitly know to make sure to keep another pointer to it. Is there a cleaner way to do this from within my AlertView class?

You can use the willMoveToSuperview: callback (

-(void)willMoveToSuperview:(UIView *)newSuperview {
    if (newSuperview == nil) {    
        if ([self.delegate respondsToSelector:@selector(alertViewWillDismiss:)]) {
            [self.delegate alertViewWillDismiss:self];
        }
    }
}

It will be called before the view is deallocated, and just before it's been truly removed from the superview (with newSuperview == nil ).

EDIT: If you want it to be just after it's been (re)moved – use didMoveToSuperview:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM