runtime实用操作-AssociatedObject

2016-04-23  本文已影响76人  kuperxu

UIGestureRecognizer

缓解UIGestureRecognizer的操作压力,用一个block解决掉,不同的手势间的调用。
主要代码

#import "UIGestureRecognizer+block.h"
#import <objc/runtime.h>
#import <objc/message.h>

static const int target_key;

@implementation UIGestureRecognizer (block)

+(instancetype)xjg_gestureRecognizerWithActionBlcok:(XJGestureBlock)block{
    return [[self alloc]initWithActionBlock:block];
}

-(instancetype)initWithActionBlock:(XJGestureBlock)block{
    self = [self init];//先init初始化成功,调用的-方法表示这个self已经是一个实例,每次将实例和block绑定。如果用类对象绑定就只能产生一种效果不行~
    [self addActionBlcok:block];
    [self addTarget:self action:@selector(invoke:)];
    return self;
}

- (void)addActionBlcok:(XJGestureBlock)block{
    if(block){
        objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
}
- (void)invoke:(id)sender{
    XJGestureBlock block=objc_getAssociatedObject(self, &target_key);
    if(block)
        block(sender);
}

@end

github源码

UIAlertView

多个alertview造成代码冗余

//调用代码
- (void)firstClick{
    UIAlertView *al = [[UIAlertView alloc]initWithTitle:@"first" message:@"ok" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"OK", nil];
    al.block = ^(UIAlertView *alert,NSUInteger index){
        if(index ==1)
            NSLog(@"001");
    };
    [al show];
}
//类别代码
#import "UIAlertView+block.h"
#import <objc/runtime.h>
#import <objc/message.h>

@interface UIAlertView ()<UIAlertViewDelegate>

@end
@implementation UIAlertView (block)

- (void)setBlock:(JGAlertBlock)block{
    objc_setAssociatedObject(self, @selector(block), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    self.delegate = self;
}

- (JGAlertBlock)block{
    return objc_getAssociatedObject(self, @selector(block));
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(self.block)
        self.block(alertView,buttonIndex);
}

@end

github源码
看了这个风格你就能理解为什么苹果iOS9要废弃alertview转型UIAlertViewController,在多个alert实在是很难管理,好多delegate,代码冗余。

上面是两种不同的使用风格,第一个在非代理情况下给不同的手势填了了一个block。区分多个手势
第二个在有代理情况下区分不同的alert,都是使用了associated特性。方式却有不同。仔细思考

上一篇下一篇

猜你喜欢

热点阅读