iOS-关联对象

2017-04-27  本文已影响0人  黑酒一
以UIAlertView为例,在创建时,对事件进行处理。
// 设置关联对象时,通常使用静态全局变量做键。
static void * EOCMyAiertViewKey = "EOCMyAiertViewKey";

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Question" message:@"What do you want to do?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Continue", nil];

void(^ block)(NSInteger) = ^(NSInteger buttonIndex) {
    
    // 在这里判断ButtonIndex 做相应处理
};

objc_setAssociatedObject(alert, EOCMyAiertViewKey, block, OBJC_ASSOCIATION_COPY);

[alert show];

#pragma mark - alertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    void(^ block)(NSInteger) = objc_getAssociatedObject(alertView, EOCMyAiertViewKey);
    block(buttonIndex);
}
上一篇 下一篇

猜你喜欢

热点阅读