Я сделал смесь между ответом Кендалла и использованием блоков в одном из моих классов контроллера базового представления. Теперь я могу использовать AlertView и ActionSheets с блоками, что значительно улучшает читабельность. Вот как я это сделал:
В .h моего ViewController я объявляю тип блока (необязательно, но рекомендуется)
typedef void (^AlertViewBlock)(UIAlertView*,NSInteger);
Также я объявляю изменяемый словарь, в котором будут храниться блоки для каждого предупреждения:
NSMutableDictionary* m_AlertViewContext;
В файле реализации я добавляю метод для создания AlertView и сохранения блока:
-(void)displayAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelButtonTitle withBlock:(AlertViewBlock)execBlock otherButtonTitles:(NSArray *)otherButtonTitles
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles: nil];
for (NSString* otherButtonTitle in otherButtonTitles) {
[alert addButtonWithTitle:otherButtonTitle];
}
AlertViewBlock blockCopy = Block_copy(execBlock);
[m_AlertViewContext setObject:blockCopy forKey:[NSString stringWithFormat:@"%p",alert]];
Block_release(blockCopy);
[alert show];
[alert release];
}
Обратите внимание, что я получаю те же атрибуты, что и конструктор UIAlertView, но делегат (который будет самостоятельным). Также я получаю объект AlertViewBlock, который я сохраняю в изменяемом словаре m_AlertViewContext.
Затем я показываю предупреждение, как обычно.
В обратных вызовах делегата я вызываю блок и задаю ему параметры:
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
AlertViewBlock block = [m_AlertViewContext objectForKey:blockKey];
block(alertView,buttonIndex);
[m_AlertViewContext removeObjectForKey:blockKey];
}
- (void)alertViewCancel:(UIAlertView *)alertView {
NSString* blockKey = [NSString stringWithFormat:@"%p",alertView];
[m_AlertViewContext removeObjectForKey:blockKey];
}
Теперь, когда мне нужно использовать AlertView, я могу назвать его так:
[self displayAlertViewWithTitle:@"Title"
message:@"msg"
cancelButtonTitle:@"Cancel"
withBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"DO ACTION"]){
[self doWhatYouHaveToDo];
}
} otherButtonTitles:[NSArray arrayWithObject:@"DO ACTION"]];
Я сделал то же самое для ActionSheet, и теперь их действительно легко использовать.
Надеюсь, это поможет.