objc_setAssociatedObject与Block的简单使用

  • UIAlertView的扩展

.h文件

#import 
typedef void (^successBlock)(NSInteger buttonIndex);

@interface UIAlertView (Block)

- (void)showWithBlock:(successBlock)block;

@end

.m文件


#import "UIAlertView+Block.h"
#import 

static const char alertKey;

@implementation UIAlertView (Block)

- (void)showWithBlock:(successBlock)block
{
    if (block)
    {
        objc_setAssociatedObject(self, &alertKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        self.delegate = self;
    }
    
    [self show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    successBlock block = objc_getAssociatedObject(self, &alertKey);
    
    block(buttonIndex);
}

@end
  • UIButton的扩展

.h文件


#import 

typedef void (^btnBlock)();

@interface UIButton (Block)

- (void)handelWithBlock:(btnBlock)block;

@end

.m文件


#import "UIButton+Block.h"
#import 

static const char btnKey;

@implementation UIButton (Block)

- (void)handelWithBlock:(btnBlock)block
{
    if (block)
    {
        objc_setAssociatedObject(self, &btnKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    
    [self addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)btnAction
{
    btnBlock block = objc_getAssociatedObject(self, &btnKey);
    block();
}

@end

tips: 使用objc_setAssociatedObject,需要引入头文件 #import


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

这两个方法可以让一个对象和另一个对象关联,就是说一个对象可以保持对另一个对象的引用,并获取那个对象。有了这些,就能实现属性功能了。 policy可以设置为以下这些值:

enum {OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01
OBJC_ASSOCIATION_COPY = 01403
};

你可能感兴趣的:(objc_setAssociatedObject与Block的简单使用)