runtime實用操作-AssociatedObject

UIGestureRecognizer

緩解UIGestureRecognizer的操作壓力,用一個block解決掉,不同的手勢間的調(diào)用。
主要代碼

#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初始化成功,調(diào)用的-方法表示這個self已經(jīng)是一個實例,每次將實例和block綁定。如果用類對象綁定就只能產(chǎn)生一種效果不行~
    [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造成代碼冗余

//調(diào)用代碼
- (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源碼
看了這個風(fēng)格你就能理解為什么蘋果iOS9要廢棄alertview轉(zhuǎn)型UIAlertViewController,在多個alert實在是很難管理,好多delegate,代碼冗余。

上面是兩種不同的使用風(fēng)格,第一個在非代理情況下給不同的手勢填了了一個block。區(qū)分多個手勢
第二個在有代理情況下區(qū)分不同的alert,都是使用了associated特性。方式卻有不同。仔細思考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,327評論 4 61
  • “慈云書畫院‘’緣起 九州風(fēng)雅,乾坤朗朗。諸子百家,競相鳴放??酌现?,禮儀安邦。老莊思想,自然...
    歸一堂閱讀 855評論 0 3
  • 尖山朝雨漱清晨,濕鷺沉沉友情深。 橫道下馬君送餅,有心增暖寄書痕。 敬君朗誦歌一曲,氣勢奔流感心誠。 君子相思皆逑...
    北山微光閱讀 266評論 0 0
  • 第二十九章 化人 只聽砰的一聲,湖面濺起十米高的水柱。 一個龐大的身影出現(xiàn)在了眾人眼中,這是一...
    不方便的面閱讀 445評論 10 19

友情鏈接更多精彩內(nèi)容