Objective c 目标C,一个关于迭代协议变量的问题
假设我已经定义了自己的协议,并将其命名为NeighborNodeListener。 我有一个NSMutableArray,它包含实现协议的对象。 现在,我想遍历NSMUTABLE数组,并为数组中的所有对象调用协议中定义的方法之一Objective c 目标C,一个关于迭代协议变量的问题,objective-c,protocols,Objective C,Protocols,假设我已经定义了自己的协议,并将其命名为NeighborNodeListener。 我有一个NSMutableArray,它包含实现协议的对象。 现在,我想遍历NSMUTABLE数组,并为数组中的所有对象调用协议中定义的方法之一 for(id <NeighborNodeListener> object in listeners){ [object firstMethod];//first method is defined in the protocol } fo
for(id <NeighborNodeListener> object in listeners){
[object firstMethod];//first method is defined in the protocol
}
for(侦听器中的id对象){
[object firstMethod];//协议中定义了第一个方法
}
我想做点像这样的事,但没用。
我想在Objective C中执行的代码在Java中看起来是这样的
List<NeighborNodeListener> listeners = new ArrayList<NeighborNodeListener>();
Iterator<NeighborNodeListener> iter = listeners.iterator();
while (iter.hasNext()) {
iter.next().firstMethod();
}
List listeners=new ArrayList();
迭代器iter=listeners.Iterator();
while(iter.hasNext()){
iter.next().firstMethod();
}
Objective-C在类型方面比Java稍差一点,因此您需要在运行时进行检查
请注意,下面的两个代码块做相同的事情——除了第一个检查object
是否完全符合协议,而后者只检查您想要调用的方法
for (id object in listeners)
{
if ([object conformsToProtocol:@protocol(myProtocol)])
{
[object firstMethod];//first method is defined in the protocol
}
else
{
[NSException raise:NSInternalInconsistencyException format:@"objects in the listeners array must confirm to myProtocol"];
}
}
或者
请详细说明“不起作用”的含义。这并不是非常具体,从你的代码来看,似乎没有什么问题。。。
for (id object in listeners)
{
if ([object respondsToSelector:@selector(firstMethod)])
{
[object firstMethod];//first method is defined in the protocol
}
else
{
[NSException raise:NSInternalInconsistencyException format:@"objects in the listeners array must confirm to myProtocol"];
}
}