Objective-C协议作为另一个协议的参数

时间:2022-09-07 08:47:31

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).

我正在尝试创建一个访问我的web api的通用存储库(模式)。我无法理解协议如何在objective-c中工作(我来自c#,其中接口有点不同)。

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?

我想要做的是让ProtocolA成为另一个ProtocolB中的参数,然后是ProtocolA上ProtocolB访问方法的实现,因为传入ProtocolB的对象必须实现ProtocolA本身。我正确地考虑了吗?

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

1 个解决方案

#1


6  

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

它不起作用,因为id类型已经是指向Objective-c对象的指针。

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.

不是id *,否则参数将是指向Objective-C对象的指针,除非得到具体值,否则不能向它发送消息。

#1


6  

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

它不起作用,因为id类型已经是指向Objective-c对象的指针。

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.

不是id *,否则参数将是指向Objective-C对象的指针,除非得到具体值,否则不能向它发送消息。