crizzwald
crizzwald

Reputation: 1037

Objective-C protocol as parameter in another protocol

I am trying to create a generic repository (pattern) that accesses my web api. I am having trouble understanding how protocols work in objective-c (I come from c# where interfaces are a bit different).

What I am trying to do is have ProtocolA be a parameter in another ProtocolB and then in the implementation of ProtocolB access methods on ProtocolA, since the object passed in to ProtocolB must implement ProtocolA itself. Am I thinking about that correctly?

This is what I have thus far, but can't seem to get it to work - maybe my logic is wrong:

//PGenericModel.h
@protocol PGenericModel <NSObject>
- (void)testMethod;
@end


//PGenericRepository.h
#import "PGenericModel.h"
@protocol PGenericRepository <NSObject>
@required
- (void)Get:(id<PGenericModel>*)entity;
@end


//GenericRepository.m
#import "GenericRepository.h"
@implementation GenericRepository
- (void)Get:(id<PGenericModel>*)entity
{
    //GET
    [entity testMethod] <-- this doesn't work...
}
@end

Upvotes: 0

Views: 269

Answers (1)

Jack
Jack

Reputation: 133629

It is not working because an id type is already a pointer to an Objective-c object.

So you should declare the signature as

- (void)Get:(id<PGenericModel>)entity

not id<PGenericModel>*, otherwise the argument would be a pointer to a pointer to an Objective-C object, you can't send messages to it unless you get the concrete value.

Upvotes: 7

Related Questions