在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区分进行分支处理时会有一种重构的冲动呢?