我在SCNRenderer上写了一个类别,它添加了一些相机实用程序方法。 这些相同的方法对SCNView和SCNLayer同样有用。 此类别相关的所有三个类都符合SCNSceneRenderer。 是否可以编写一个不适用于特定类的类别,而是适用于符合特定协议的所有类?
I have written a category on SCNRenderer that adds some camera utility methods. Those same methods would be equally useful to SCNView and SCNLayer. All three of the classes to which this category would be relevant conform to SCNSceneRenderer. Is it possible to write a category that applies not to a specific class, but to all classes that conform to a particular protocol?
最满意答案
最简单的方法是编写一些带有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> @endThe simplest way of doing this would be to write some utility functions that take an SCNSceneRenderer object:
void ABCDoSomethingUseful(id<SCNSceneRenderer> renderer) { //... } void ABCDoSomethingElseUseful(id<SCNSceneRenderer> renderer) { //... }If you want to use the method call syntax, or want to be able to override the implementation in subclasses, another option would be to implement the methods as a category on 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 { //... } @endthen expose them in a protocol:
// This goes in a header file: @protocol MyProtocol <NSObject> - (void)abc_doSomethingElseUseful; - (void)abc_doSomethingUseful; @endand add an interface-only category for each class that conforms to SCNSceneRenderer declaring that it also conforms to your protocol:
// This also goes in a header file: @interface SCNLayer (MyProtocolConformance) <MyProtocol> @end @interface SCNView (MyProtocolConformance) <MyProtocol> @end更多推荐
发布评论