iPhone开源系列:UIAlertView-Block

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


本文出自 “林家男孩” 博客,请务必保留此出处http://bj007.blog.51cto.com/1701577/635845

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值