且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在“id"类型的对象上找不到读取数组元素的预期方法

更新时间:2023-11-16 15:34:52

首先,我假设 group 实际上不是 NSArray,但实际上是:

First, I'm assuming that group is not actually an NSArray, but is in fact:

id<MyProtocol> _Nonnull group

这表示 group 是一些符合 MyProtocol 的对象".MyProtocol 中没有任何内容表明该对象可以下标.如果你希望它可以被索引下标,那么你需要在协议中这样说:

This says that group is "some object that conforms to MyProtocol". Nothing in MyProtocol says that this object can be subscripted. If you want it to be subscriptable by indexes, then you need to say this in the protocol:

@protocol MyProtocol <NSObject>
- (id<MyProtocol>)objectAtIndexedSubscript:(NSUInteger)idx;
...

而且您当然需要在任何符合条件的情况下实现 objectAtIndexedSubscript:(但这似乎已经是这种情况,因为它在您投射时有效).

And you of course need to implement objectAtIndexedSubscript: in anything that conforms (but this seems to already be the case, since it works when you cast it).