Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol as method argument

Tags:

objective-c

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.

like image 491
user1594959 Avatar asked Feb 20 '23 12:02

user1594959


1 Answers

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.

like image 91
zoul Avatar answered Mar 04 '23 17:03

zoul