Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an ObjC class object conform to a protocol?

Is there a way to indicate to the compiler that a class object conforms to a protocol?

As I understand, by creating +(void)foo class methods, an instance of that class object will have those methods as instance methods. So, as long as I create +(void)foo methods for all required protocol methods, I can have a class object act as a delegate.

My problem of course is that in the class's header file, I only know how to indicate that instances of the class conform to the protocol (as is typically the case). So, the best I've figured out is to cast the class object like so:

something.delegate = (id<SomethingDelegate>)[self class]

Any ideas?

Related, but different: ObjC: is there such a thing as a "class protocol"?

like image 222
Doug Avatar asked Apr 09 '12 02:04

Doug


People also ask

What is a protocol OBJC?

Advertisements. Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. Protocols are implemented in the classes conforming to the protocol.

How do you conform to a protocol in Objective-C?

Objective-C Language Protocols Conforming to Protocols It is also possible for a class to conform to multiple protocols, by separating them with comma. Like when conforming to a single protocol, the class must implement each required method of each protocols, and each optional method you choose to implement.

What is Xcode protocol?

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.


1 Answers

What you're doing now is correct as it will silence warnings which is your goal. You will be sending the class object messages defined in the protocol for instances which is a bit confusing, but the runtime doesn't care.

Think about it this way: you want to set a delegate to an object that responds to the messages defined in the protocol. Your class does this, and your class is also an object. Therefore, you should treat your class like an object that conforms to that protocol. Therefore, what you've written is completely correct (based on what you're trying to do).

One thing to note, though, is this class will not properly respond to conformsToProtocol:. This is generally okay for a delegate setup anyway (delegates don't usually check if the class conforms — they just check if it can respond to a selector).

As a side note, one thing you can do syntactically is:

Class<SomethingDelegate> variable = (Class<SomethingDelegate>)[self class];

The difference here is that the compiler will use the class methods from the protocol instead of instance messages. This is not what you want in your case, though.

like image 196
wbyoung Avatar answered Oct 01 '22 00:10

wbyoung