user1594959
user1594959

Reputation: 39

Protocol as method argument

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

The method subset is declared in HouseProtocol, while class House 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 taking a HouseProtocol argument:

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

This method should use methods of house, but only those which are accessible in HouseProtocol. Meaning method foo but not method bar.

Is the above correct, and how is the foo method called inside somemethod? Working code appreciated.

Upvotes: 4

Views: 3028

Answers (1)

zoul
zoul

Reputation: 104125

This is correct. Calling methods on hp works as usual:

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

Note that if you don’t really need the protocol (like if the code is really simple and writing a protocol would be clearly overkill), you can simply use the id type:

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

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

Judging from the question title, what got you confused is the way you think about the type of the hp variable – id<HouseProtocol> is not a protocol, it’s “something that implements HouseProtocol”. This is why you can call methods on hp the usual way, as it’s just some kind of object.

Upvotes: 8

Related Questions