Protocol as an argument to a method

I want the method to have access to a subset of the method declared in the same class. Obviously, this can be achieved by protocols.

A subset of the method is declared in HouseProtocol, and the House class implements its methods.

@protocol HouseProtocol <NSObject> -(void) foo; @end 

.

 @interface House : NSObject <HouseProtocol> -(void) foo; -(void) bar; @end 

Somewhere else in another class, a method is defined with the HouseProtocol argument:

 -(void) somemethod:(id<HouseProtocol>)hp; 

This method should use home methods, but only those available at HouseProtocol. The value of the foo method, but not the method bar.

Is this correct, and how is the foo method called inside somemethod? The working code is appreciated.

+4
source share
1 answer

It is right. The calling methods on hp work as usual:

 - (void) somemethod: (id<HouseProtocol>) hp { [hp foo]; } 

Please note: if you really don’t need the protocol (for example, if the code is really simple and the protocol record will be obviously full), you can simply use the id type:

 - (void) somemethod: (id) hp { [hp foo]; } 

The only catch in this case is that the compiler needs to know that -foo exists.

Judging by the title of the question, what confuses you is how you think about the type of the variable hp - id<HouseProtocol> not a protocol, its "something that implements HouseProtocol ". This is why you can call methods on hp usual way, as its just some kind of object.

+8
source

All Articles