在iPhone项目开发的过程当中,从新造轮子的事情家常便饭,一方面源于开发者的“自我”心态,但更多的是由于对开发项目的不了解。但愿经过这样一个系列和你们一块儿发现和挖掘项目开发中经常使用的开源项目,共同改进iPhone应用开发。git
UIAlertView和UIActionSheet都采用了Delegate模式,在同一个视图控制器中使用多个UIAlertView或UIActionSheet时控制器须要同时充当它们的delegate,这种状况下处理函数中一般须要经过tag进行区分后处理。这样就常常会形成以下代码:github
- (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 {
}
}ide
这种针对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];
};this
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];code
有了这样一个项目,是否是再次看到根据tag区分进行分支处理时会有一种重构的冲动呢?事件