【问题标题】:Best way check if delegate responds to optional selector检查委托是否响应可选选择器的最佳方法
【发布时间】:2013-09-28 09:13:07
【问题描述】:

我已经习惯将发送@optional委托的方法包装到:

if ([self.delegate respondsToSelector:@selector(method:)]) {
    [self.delegate method:obj];
}

效果不错,但是如果delegate的方法很多,就好像在复制respondToSelector:的代码...

在某个时间点,我将respondsToSelector: 放在单独的方法中:

//ignore warning
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

- (void)performDelegateSelector:(SEL)selector withObject:(id)obj {

    if ([self.delegate respondsToSelector:selector]) {
        [self.delegate performSelector:selector withObject:obj];
    }
}

结果我只有一个 respondToSelector: 检查,但它看起来仍然没有得到很好的改进。

[self performDelegateSelector:@selector(method:) withObject:self];

你怎么看?使用一些帮助器或类别来包装发送所有@optional 委托的方法是否有意义,或者这是不应该改进的东西?

【问题讨论】:

    标签: iphone ios delegates


    【解决方案1】:

    性能方面,这取决于您对委托的用途,它是否直接影响 UI(在这种情况下,您希望获得更快的响应时间)等。

    一个很好的速度优化是在您第一次设置委托时将委托实现的所有方法注册到一个数据结构中。你可以这样做:

    struct {
        unsigned int myFirstMethod:1;
        unsigned int mySecondMethod:1;
    } delegateRespondsTo;
    
    -(void)setDelegate:(id<MyProtocol>)delegate
    {
        self.delegate = delegate;
        delegateRespondsTo.myFirstMethod = [delegate respondsToSelector:@selector(myFirstMethod)];
        delegateRespondsTo.mySecondMethod = [delegate respondsToSelector:@selector(mySecondMethod)];
    }
    

    那么你可以简单地做

    if ( delegateRespondsTo.myFirstMethod )
        [self.delegate myFirstMethod];
    

    查看这个很棒的answer 以获得更详尽的解释。

    【讨论】:

      【解决方案2】:

      您可以为此使用蹦床。蹦床是将消息转发到另一个对象的对象。这是一个简单的 DelegateTrampoline。

      #import <objc/runtime.h>
      
      @interface DelegateTrampoline : NSObject
      - (id)initWithProtocol:(Protocol *)protocol delegate:(id)delegate;
      @end
      

      #import "DelegateTrampoline.h"
      
      @interface DelegateTrampoline ()
      @property (nonatomic) Protocol *protocol;
      @property (nonatomic, weak) id delegate;
      @end
      
      @implementation DelegateTrampoline
      
      - (id)initWithProtocol:(Protocol *)protocol delegate:(id)delegate {
        self = [super init];
        if (self) {
          _protocol = protocol;
          _delegate = delegate;
        }
        return self;
      }
      
      - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
        // Look for a required method
        struct objc_method_description desc = protocol_getMethodDescription(self.protocol, selector, YES, YES);
        if (desc.name == NULL) {
          // Maybe it's optional
          desc = protocol_getMethodDescription(self.protocol, selector, NO, YES);
        }
        if (desc.name == NULL) {
          [self doesNotRecognizeSelector:selector]; // Raises NSInvalidArgumentException
          return nil;
        }
        else {
          return [NSMethodSignature signatureWithObjCTypes:desc.types];
        }
      }
      
      - (void)forwardInvocation:(NSInvocation *)invocation {
        SEL selector = [invocation selector];
        if ([self.delegate respondsToSelector:selector]) {
          [invocation setTarget:self.delegate];
          [invocation invoke];
        }
      }
      
      @end
      

      您将如何使用它:

      @interface MyObject ()
      @property (nonatomic) id delegateTrampoline;
      @end
      ...
      self.delegateTrampoline = [[DelegateTrampoline alloc] initWithProtocol:@protocol(MyProtocol)
                                                                    delegate:delegate];
      
      [self.delegateTrampoline myobject:self didSomethingAtIndex:1];
      @end
      

      一些注意事项:

      • 与其他方法相比,这非常慢。它需要创建一个NSInvocation 对象,这可能比简单的方法调用慢数百倍。也就是说,除非您在紧密循环中调用您的委托方法,否则这可能不是问题。
      • 您必须将delegateTrampoline 声明为id 类型。这允许您将任意选择器传递给它。但这也意味着编译器无法检测您是否将选择器传递给delegateTrampoline,而该选择器不在协议中。如果你这样做,你会在运行时崩溃。编译器可以检测您是否传递了一个完全未知的选择器,因此它会捕获简单的拼写错误。

      【讨论】:

      • 听起来不错,但我的意思是 - 如何减少代码量,而不是降低性能。如果执行了很多委托的方法,它会影响应用程序的性能
      • 如果你的意思是一打或两打电话,这对性能没有显着影响。如果你有很多,你的意思是成百上千的调用在一个紧密的循环中,那么是的,那么它可能会对性能产生影响。一纳秒和一毫秒之间的差异是巨大的,但在十几次调用中,您永远不会注意到差异。
      • 我在这里找到了类似的方法borkware.com/rants/agentm/elegant-delegation using NSProxy
      【解决方案3】:

      除了@micantox 提供的答案之外,我还要补充一点,您可以使用NS_OPTIONS 来定义bitmask,而不是struct。

      typedef NS_OPTIONS (NSUInteger, MyDelegateOptions) 
      { 
        MyDelegateOptionDidFinishedWithTaskOne = 1 << 0,
        MyDelegateOptionDidFinishedWithTaskTwo = 1 << 1,
        MyDelegateOptionDidFinishedWithTaskThree = 1 << 2
      };
      

      然后您可以创建可以容纳bitmask 的属性:

      @property (nonatomic, assign) MyDelegateOptions delegateOptions;

      并检查委托respondsToSelector:在你的设置器中是否像

      - (void)setDelegate:(id<MyDelegateProtocol>)delegate
      {
        _delegate = delegate;
        if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskOne:)]) {
        {
          self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskOne;
        }
      
        if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskTwo:)]) {
        {
          self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskTwo;
        }
      
        if ([delegate respondsToSelector:@selector(myDelegateDidFinishedWithTaskThree:)]) {
        {
          self.delegateOptions = self.delegateOptions | MyDelegateOptionDidFinishedWithTaskThree;
        }
      }
      

      然后您可以使用bitwise AND 简单地检查分配的位模式

      if (self.delegateOptions & MyDelegateOptionDidFinishedWithTaskOne) {
          [self.delegate myDelegateDidFinishedWithTaskTwo:myResult];
      }
      

      如您所见,如果 MyDelegateOptionDidFinishedWithTaskOne 的位设置为 1,即使还设置了其他位,bitwise AND 的使用也会返回 true。

      因此,如果您假设 delegate 在您的设置器中进行了检查,并且基于此,您的 delegateOptions 持有 00000111 的位模式,而您的 MyDelegateOptionDidFinishedWithTaskOne 表示 00000001 然后只需使用bitwise AND

      00000111 & 00000001 = 00000001

      您将获得带有条件语句的true。

      值得注意的是,在您只需要检查一次或两次 delegate 的情况下,这样做是多余的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        相关资源
        最近更新 更多