Search code examples
iosobjective-cuialertview

Category of UIAlertView need callback for alert button click iOS


My scenario is as follows

1) I created a Category for UIAlertView class

//UIAlertView+Remove.m file
#import "UIAlertView+Remove.h"

@implementation UIAlertView (Remove)

- (void) hide {
    [self dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)removeNotificationObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
}

@end

2)Added a notification to UIAlertView object when its show

3)And I want to call removeNotificationObserver method when user click on any button in alertview to remove notification observer.

My tried out scinerios,

  • Calling its from - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex delegate is not possible here because of delegate is not properly set to all alertview objects.

  • Called it from a -dealloc method in category but -dealloc is not triggering when alertview close

Can anybody help me to get through this?


Solution

  • thank you for the responses!

    Finally, I solved it myself by implementing SubClass for UIAlertView instead of using Category. Here I commented my code snippet, it may be helpful for those who experience same issue

    //UIAlertView_AutoClose.m file
    
    #import "UIAlertView_AutoClose.h"
    
    @implementation UIAlertView_AutoClose
    
    - (id)initWithTitle:(NSString *)title
                message:(NSString *)message
               delegate:(id)delegate
      cancelButtonTitle:(NSString *)cancelButtonTitle
      otherButtonTitles:(NSString *)otherButtonTitles, ...
    {
        if(delegate == nil){
            delegate = self;
        }
    
        return [super initWithTitle:title message:message delegate:delegate cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];
    }
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
        NSLog(@"Reached alertview_autoclose");
    }
    
    - (void) hide {
        [self dismissWithClickedButtonIndex:0 animated:YES];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:NSCalendarDayChangedNotification object:nil];
    }
    
    @end