I\'m pretty new to objective C and I\'m just trying to figure out if I can use a block or a selector as the UIAlertViewDelegate argument for UIAlertView - and which is more
Great idea. Here it is. Just like alert view, except adds a block property that's invoked when the alert is dismissed. (Edit - I've simplified this code since the original answer. Here's what I use now in projects)
// AlertView.h
//
#import <UIKit/UIKit.h>
@interface AlertView : UIAlertView
@property (copy, nonatomic) void (^completion)(BOOL, NSInteger);
- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles;
@end
//
// AlertView.m
#import "AlertView.h"
@interface AlertView () <UIAlertViewDelegate>
@end
@implementation AlertView
- (id)initWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSArray *)otherButtonTitles {
self = [self initWithTitle:title message:message delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
if (self) {
for (NSString *buttonTitle in otherButtonTitles) {
[self addButtonWithTitle:buttonTitle];
}
}
return self;
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (self.completion) {
self.completion(buttonIndex==self.cancelButtonIndex, buttonIndex);
self.completion = nil;
}
}
@end
You can extend this idea to supply blocks for other delegate methods, but the didDismiss is the most common.
Call it like this:
AlertView *alert = [[AlertView alloc] initWithTitle:@"Really Delete" message:@"Do you really want to delete everything?" cancelButtonTitle:@"Nevermind" otherButtonTitles:@[@"Yes"]];
alert.completion = ^(BOOL cancelled, NSInteger buttonIndex) {
if (!cancelled) {
[self deleteEverything];
}
};
[alert show];
Simply use REKit. It's similar to BlocksKit, but it's more powerful.
Check out UIAlertView-Blocks category on Github. I wrote this and is very easy to use and works well.
Good luck.
Here is my implementation, seems like it's similar to most answers here: http://stavash.wordpress.com/2013/01/31/quick-tip-uialertview-with-a-block-callback/
Here is another useful library to do the same. http://bit.ly/ichalrtvw
Code here: http://bit.ly/ichalertview
Check out this UIAlertView-Blocks category on github. I use this and it works well.