给UIAlertView添加block实现

  • 使用"关联对象"(Associated Object)存放自定义数据

可以给某对象关联许多其它对象,这些对象通过"键"来区分。存储对象值得时候,可以指明"存储策略"(storage policy),用以维护相应的"内存管理语义"。
下列方法可以管理关联对象:

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

此方法以给定的键和策略为某对象设置关联对象值。

id objc_getAssociatedObject(id object, void *key)

此方法根据给定的键从某对象中获取相应的关联对象值。

void objc_removeAssociatedObjects(id object)

此方法移除指定对象的全部关联对象。

  • UIAlertView的block实现

typedef void(^CompleteBlock) (NSInteger buttonIndex);

@interface UIAlertView (Block)

// 用Block的方式回调,这时候会默认用self作为Delegate
- (void)showAlertViewWithCompleteBlock:(CompleteBlock) block;

@end
// 需要引入#import 头文件
@implementation UIAlertView (Block)

static void *key = "NTOAlertView";

- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block
{
    if (block) {
        ////移除所有关联
        objc_removeAssociatedObjects(self);
        objc_setAssociatedObject(self, key, block, OBJC_ASSOCIATION_COPY);
        ////设置delegate
        self.delegate = self;
    }
    ////show
    [self show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    ///获取关联的对象,通过关键字。
    CompleteBlock block = objc_getAssociatedObject(self, key);
    if (block) {
        ///block传值
        block(buttonIndex);
    }
}

使用起来很简单

// 需要引入#import "UIAlertView+Block.h"头文件
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"myself title" message:@"alert message" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
             NSLog(@"您点击了%ld", buttonIndex);
        }];

你可能感兴趣的:(给UIAlertView添加block实现)