【问题标题】:Set default handler for "unrecognized selector" exception为“无法识别的选择器”异常设置默认处理程序
【发布时间】:2012-11-15 04:02:49
【问题描述】:

在 Objective-C 中,有没有办法设置默认处理程序以避免 unrecognizedselector 异常?我想让NSNULLNSNumber 响应NSString 中的所有方法。

谢谢!

【问题讨论】:

    标签: objective-c cocoa nsstring unrecognized-selector


    【解决方案1】:

    您可以使用类别将方法添加到NSNullNSNumber 类。阅读The Objective-C Programming Language 中的类别。

    您可以实现methodSignatureForSelector:forwardInvocation: 来处理任何消息,而无需明确定义要处理的所有消息。在NSObject Class Reference 中了解它们。

    【讨论】:

      【解决方案2】:

      要处理“无法识别的选择器”异常,我们应该重写两个方法:

      - (void)forwardInvocation:(NSInvocation *)anInvocation;
      - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector;
      

      在这种情况下,如果我们希望 NSNull 在发生“无法识别的选择器”异常时执行 NSSString 方法,我们应该这样做:

      @interface NSNull (InternalNullExtention)
      @end
      
      
      
      @implementation NSNull (InternalNullExtention)
      
      - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
      {
          NSMethodSignature* signature = [super methodSignatureForSelector:selector];
          if (!signature) {
              signature = [@"" methodSignatureForSelector:selector];
          }
          return signature;
      }
      
      - (void)forwardInvocation:(NSInvocation *)anInvocation
      {
          SEL aSelector = [anInvocation selector];
      
          if ([@"" respondsToSelector:aSelector])
              [anInvocation invokeWithTarget:@""];
          else
              [self doesNotRecognizeSelector:aSelector];
      }
      @end
      

      【讨论】:

        【解决方案3】:

        有。查看 forwardInvocation 的示例:在此处的 NSObject 文档中: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html

        基本上你会覆盖 forwardInvocation 并且当一个对象没有匹配某个给定选择器的方法时调用它。

        【讨论】:

        • 谢谢!我注意到除了 - (void)forwardInvocation:(NSInvocation )anInvocation,我还需要实现 - (NSMethodSignature)methodSignatureForSelector:(SEL)selector
        猜你喜欢
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多