UIAlertView和UIActionSheet都采用了Delegate模式,在同一个视图控制器中使用多个UIAlertView或UIActionSheet时控制器需要同时充当它们的delegate,这种情况下处理函数中通常需要通过tag进行区分后处理。这样就经常会造成如下代码:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([alertView tag] == LOGIN_ERROR_ALERT) { // it's alert for login error
if (buttonIndex == 0) { // and they clicked OK.
// do stuff
}
}
else if ([alertView tag] == UPDATE_ERROR_ALERT) { // it's alert for update error
if (buttonIndex == 0) { // and they clicked OK.
// do stuff
}
}
else {
}
}
这种针对tag的分支判断就会影响到代码可读性,并产生坏味道。UIAlertView-Block(https://github.com/jivadevoe/UIAlertView-Blocks)项目就可以克服这样的问题。该项目提供了可以使用代码块来处理按钮事件的UIAlertView和UIActionSheet的Category,示例代码如下:
RIButtonItem *cancelItem = [RIButtonItem item];
cancelItem.label = @"No";
cancelItem.action = ^
{
// this is the code that will be executed when the user taps "No"
// this is optional... if you leave the action as nil, it won't do anything
// but here, I'm showing a block just to show that you can use one if you want to.
};
RIButtonItem *deleteItem = [RIButtonItem item];
deleteItem.label = @"Yes";
deleteItem.action = ^
{
// this is the code that will be executed when the user taps "Yes"
// delete the object in question...
[context deleteObject:theObject];
};
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Delete This Item?" message:@"Are you sure you want to delete this really important thing?" cancelButtonItem:cancelItem otherButtonItems:deleteItem, nil]; [alertView show]; [alertView release];
有了这样一个项目,是不是再次看到根据tag区分进行分支处理时会有一种重构的冲动呢?
本文出自 “林家男孩” 博客,请务必保留此出处http://bj007.blog.51cto.com/1701577/635845