开发者

Adopting a protocol from a category

I wanted to verify that this fix actually works and won't have adverse effects on my code:

I've created a static library with a MyClass.h public header, the rest of my code is all hidden. MyClass adopts the protocol MyProtocol, which is defined in MyProtocol.h. I want to keep MyProtocol.h hidden, but since MyClass.h is a public header, it can't find MyProtocol.h if I try to keep it hidden as a project header. My solution:

MyClass.h:

@interface MyClass : NSObject {
    //instance variables
}
// methods
@end

MyClass.m:

#import "MyProtocol.h"
@interface MyClass() <MyProtocol>
@end

@implementation MyClass
// implementation
@end

I haven't seen other examples of this sort of thing being done other than here: Can a category simultaneously implement a protocol?, and the problem/answers ended up being unrelated to the original question. So I wanted to be sure that this actually does what it looks like it does, and/or see if there is a better way to achieve 开发者_开发知识库what I'm trying to do.


What you're proposing is perfectly legal, and is a fine solution to your problem.

There is one subtle semantic distinction that may have muddled your google searches on this subject. By using empty parenthesis in your example, you've technically declared a "class extension", not a "category". The subtle difference is that the compiler requires the methods declared within a class extension to be implemented in the main @implementation block of your class. By contrast, the methods declared within a named category are implemented within a separate named implementation block, often within a separate .m file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜