runtime(抄)的blok

1. runtime俗称(运行时)

2.理解(优点):可以不破坏他人项目中已有的类的封装,与已有类完全分开,保持了模块化的独立性,添加自己想要添加的属性

3.实现:UIBarButtonItem已blok的形式实现

#import@interface UIBarButtonItem (BlockSupport)

//UIBarButtonItem 的标题

- (nullable instancetype)initWithTitle:(nullable NSString *)title style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock;

//UIBarButtonItem 的图片,

-(nullable instancetype)initWithImage:(nullable UIImage*)image style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock;

@end



#import "UIBarButtonItem+BlockSupport.h"

// 导入runtime

#import  

const char *barbuttonItemBlockKey = "barbuttonItemBlockKey";

@implementation UIBarButtonItem (BlockSupport)

- (instancetype)initWithTitle:(nullable NSString *)title style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock

{

self = [self initWithTitle:title style:style target:self action:@selector(handleClick)];

if (self) {

objc_setAssociatedObject(self, barbuttonItemBlockKey, clickBlock, OBJC_ASSOCIATION_COPY);

}

return self;

}

- (void)handleClick

{

void (^block)() = objc_getAssociatedObject(self, barbuttonItemBlockKey);

if (block ) {

block();

}

}

-(nullable instancetype)initWithImage:(nullable UIImage*)image style:(UIBarButtonItemStyle)style andBlock:(void(^)())clickBlock

{

self = [self initWithImage:image style:style target:self action:@selector(handleClickImage)];

if (self) {

objc_setAssociatedObject(self, barbuttonItemBlockKey, clickBlock, OBJC_ASSOCIATION_COPY);

}

return self;

}

- (void)handleClickImage

{

void (^block)() = objc_getAssociatedObject(self, barbuttonItemBlockKey);

if (block ) {

block();

}

}

@end

你可能感兴趣的:(runtime(抄)的blok)