在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區分進行分支處理時會有一種重構的衝動呢?事件