Can someone explain how the delegate to a UIAlertView
works? Is it automatically called or do I have to call it? Eg:
- (void)alertView:(UIAlertVie
Here is a wrapper for the delegate so that you can use blocks instead. The flow of execution will be the same but the flow of the code will be easier to follow. So, usage:
[YUYesNoListener yesNoWithTitle:@"My Title" message:@"My Message" yesBlock:^
{
NSLog(@"YES PRESSED!");
}
noBlock:^
{
NSLog(@"NO PRESSED!");
}];
...and here is the helper class:
typedef void(^EmptyBlockType)();
@interface YUYesNoListener : NSObject
@property (nonatomic, retain) EmptyBlockType yesBlock;
@property (nonatomic, retain) EmptyBlockType noBlock;
+ (void) yesNoWithTitle:(NSString*)title message:(NSString*)message yesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock;
@end
@implementation YUYesNoListener
@synthesize yesBlock = _yesBlock;
@synthesize noBlock = _noBlock;
- (id) initWithYesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock
{
self = [super init];
if (self)
{
self.yesBlock = [[yesBlock copy] autorelease];
self.noBlock = [[noBlock copy] autorelease];
}
return self;
}
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0 && self.noBlock)
self.noBlock();
else if (buttonIndex == 1 && self.yesBlock)
self.yesBlock();
[_yesBlock release];
[_noBlock release];
[alertView release];
[self release];
}
- (void) alertViewCancel:(UIAlertView *)alertView
{
if (self.noBlock)
self.noBlock();
[_yesBlock release];
[_noBlock release];
[alertView release];
[self release];
}
+ (void) yesNoWithTitle:(NSString*)title message:(NSString*)message yesBlock:(EmptyBlockType)yesBlock noBlock:(EmptyBlockType)noBlock
{
YUYesNoListener* yesNoListener = [[YUYesNoListener alloc] initWithYesBlock:yesBlock noBlock:noBlock];
[[[UIAlertView alloc] initWithTitle:title message:message delegate:yesNoListener cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil] show];
}
@end