您好,登錄后才能下訂單哦!
在iPhone項目開發(fā)的過程中,重新造輪子的事情屢見不鮮,一方面源于開發(fā)者的“自我”心態(tài),但更多的是因為對開發(fā)項目的不了解。希望通過這樣一個系列和大家一起發(fā)現(xiàn)和挖掘項目開發(fā)中常用的開源項目,共同改進iPhone應(yīng)用開發(fā)。
UIAlertView和UIActionSheet都采用了Delegate模式,在同一個視圖控制器中使用多個UIAlertView或UIActionSheet時控制器需要同時充當(dāng)它們的delegate,這種情況下處理函數(shù)中通常需要通過tag進行區(qū)分后處理。這樣就經(jīng)常會造成如下代碼:
- (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的分支判斷就會影響到代碼可讀性,并產(chǎn)生壞味道。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];
有了這樣一個項目,是不是再次看到根據(jù)tag區(qū)分進行分支處理時會有一種重構(gòu)的沖動呢?
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。