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.
You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject or class protocol to a protocol's inheritance list.
Adding Protocol Conformance with an Extension Existing type can be adopted and conformed to a new protocol by making use of extensions. New properties, methods and subscripts can be added to existing types with the help of extensions.
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.
Protocol is a set of methods (either optional or required) that would be implemented by the class which conforms to that protocol. While, delegate is the reference to that class which conforms to that protocol and will adhere to implement methods defined in protocol.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With