美文网首页
模拟Target-Action方式,Selector实现方法

模拟Target-Action方式,Selector实现方法

作者: _Choice_ | 来源:发表于2017-04-14 15:59 被阅读77次

在组件设计中,往往会出现需要组件去响应其他组件的场景,常用的方式有Block,Delegate,NSNotification等等。
下面我要介绍的是比较冷门的一个方法,TargetAction的方法。 方法灵感来源于UIButton的addTarget:方法。

如果我们能为自己的控件绑定好响应操作的方法,代码相较于Block块状分布会优雅的多。

首先

在控件.h文件里添加好暴露出去的方法。
并且定义两个属性,分别是SEL方法选择器和target


@property (nonatomic,weak) id target;
@property (nonatomic,assign) SEL seclector;

- (void) addTarget:(id)target
         selector:(SEL)selector;```


###实现
然后在相应的.m文件里实现
  • (void) tapAction{

    if (_target && [_target respondsToSelector:_seclector]) {

      if (!_target) {
          return;
      }
      IMP imp = [_target methodForSelector:_seclector];
      void (*func)(id,SEL,HotPointPiecesView *) = (void *)imp; //HotPointPiecesView是我创建的类,我将当前类传递出去
      func(_target,_seclector,self);
    

    }
    }

  • (void)addTarget:(id)target selector:(SEL)selector{
    if (target && selector) {
    self.target = tagret;
    self.seclector = selector;
    }
    }

其中`- (void) tapAction`方法,是手势响应方法,由于当前类是个UIView,我添加了一个手势来响应触摸操作。

###其中的坑
一开始我的`- (void) tapAction`是这么实现的:
  • (void) tapAction{

    if (_target && [_target respondsToSelector:_seclector]) {

      if (!_target) {
          return;
      }
      [_target performSelector:_seclector withObject:self];
    

    }
    }```
    紧接着Xcode报了一个警告:
    "performSelector may cause a leak because its selector is unknown".
    字面上的意思是performSelector方法会导致一个leak,因为selector是未知的。
    解决的方法:

http://stackoverflow.com/questions/7017281/performselector-may-cause-a-leak-because-its-selector-is-unknown

相关文章

网友评论

      本文标题:模拟Target-Action方式,Selector实现方法

      本文链接:https://www.haomeiwen.com/subject/xonwattx.html