Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 660
Chris C Avatar asked Jul 06 '11 01:07

Chris C


People also ask

How do you ensure the adoption of a protocol only by reference type?

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.

How do I adopt a protocol in Swift?

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.

What is protocol and how do you implement it?

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.

What is difference between protocol and delegate?

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.


1 Answers

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.

like image 164
cduhn Avatar answered Sep 18 '22 18:09

cduhn