【问题标题】:Implementing a category on all classes conforming to a protocol在符合协议的所有类上实现一个类别
【发布时间】:2013-02-07 09:49:45
【问题描述】:

我在 SCNRenderer 上写了一个类别,添加了一些相机实用程序方法。这些相同的方法对 SCNView 和 SCNLayer 也同样有用。与此类别相关的所有三个类都符合 SCNSceneRenderer。是否可以编写一个类别不适用于特定类,而是适用于符合特定协议的所有类?

【问题讨论】:

    标签: objective-c protocols scenekit


    【解决方案1】:

    最简单的方法是编写一些采用 SCNSceneRenderer 对象的实用函数:

    void ABCDoSomethingUseful(id<SCNSceneRenderer> renderer)
    {
       //...
    }
    
    void ABCDoSomethingElseUseful(id<SCNSceneRenderer> renderer)
    {
       //...
    }
    

    如果您想使用方法调用语法,或者希望能够覆盖子类中的实现,另一种选择是将方法实现为 NSObject 上的类别:

    // This goes in a source file:
    
    @interface NSObject (SCNSceneRendererConformance) <SCNSceneRenderer>
    // Surpress compiler warnings about NSObject not responding to 
    // SCNSceneRenderer's messages
    @end
    
    @implementation NSObject (MyCategory)
    
    - (void)abc_doSomethingUseful
    {
        //...
    }
    
    
    - (void)abc_doSomethingElseUseful
    {
        //...
    }
    
    @end
    

    然后在协议中公开它们:

    // This goes in a header file:
    
    @protocol MyProtocol <NSObject>
    - (void)abc_doSomethingElseUseful;
    - (void)abc_doSomethingUseful;
    @end
    

    并为每个符合 SCNSceneRenderer 的类添加一个仅接口类别,声明它也符合您的协议:

    // This also goes in a header file:
    
    @interface SCNLayer (MyProtocolConformance) <MyProtocol>
    @end
    
    @interface SCNView (MyProtocolConformance) <MyProtocol>
    @end
    

    【讨论】:

    • 我现在所做的只是忽略了这个类别对多个类有用的事实,而只是为 SCNRenderer 实现它。我认为编写实用函数的路线可能是要走的路。我可能会在某些实用程序类上将它们设为类方法。
    • 是啊...回顾 NSObject 思路上的分类,收获不多就很奇怪...
    【解决方案2】:

    我认为您不能在协议上添加类别,因为协议只定义接口而不是实现。而在类别中我们也需要实施。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多