I'm trying to use a category on UIAlertView to dismiss alert views when my app enters background state. I am implementing method swizzling (http://nshipster.com/method-swizzling/) to try to achieve this. The category methods are not being called on my UIAlertViews however.
Here is my category:
#import "UIAlertView+dismissalert.h"
#import <objc/runtime.h>
@implementation UIAlertView (dismissalert)
static NSHashTable *alertHashTable;
+ (void)load
{
SEL originalSelector = @selector(initWithContentViewController:);
SEL replacementSelector = @selector(ts_initWithContentViewController:);
Method originalMethod = class_getInstanceMethod([UIAlertView class], originalSelector);
Method replacementMethod = class_getInstanceMethod([UIAlertView class], replacementSelector);
method_exchangeImplementations(originalMethod, replacementMethod);
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(applicationDidEnterBackgroundNotification:)
name: UIApplicationDidEnterBackgroundNotification
object: nil];
}
- (id)ts_initWithContentViewController:(UIViewController *) contentViewController
{
UIAlertView *alert = [self ts_initWithContentViewController: contentViewController];
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
alertHashTable = [NSHashTable weakObjectsHashTable];
});
[alertHashTable addObject:alert];
return alert;
}
+ (void)applicationDidEnterBackgroundNotification: (NSNotification *) n
{
for (UIAlertView *alert in alertHashTable ) {
if (alert.visible) {
[alert dismissWithClickedButtonIndex:0 animated:NO];
}
}
}
I have implemented the UIAlertViewDelegate on my view controller.
Can anyone see why the category is not being called?
Thanks