您好,登錄后才能下訂單哦!
在iPhone項目開發的過程中,重新造輪子的事情屢見不鮮,一方面源于開發者的“自我”心態,但更多的是因為對開發項目的不了解。希望通過這樣一個系列和大家一起發現和挖掘項目開發中常用的開源項目,共同改進iPhone應用開發。
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區分進行分支處理時會有一種重構的沖動呢?
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。