我在SCNRenderer上写了一个类别,它添加了一些相机实用程序方法。这些相同的方法对SCNView和SCNLayer同样有用。此类别相关的所有三个类都符合SCNSceneRenderer。是否有可能编写一个不适用于特定类的类别,而是适用于符合特定协议的所有类?
答案 0 :(得分:3)
最简单的方法是编写一些带有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
答案 1 :(得分:0)
我认为你不能通过协议添加类别,因为协议只定义了接口而不是实现。而在类别中我们也需要实施。