objective-c - Objective-C ,关于遍历协议(protocol)变量的问题

标签 objective-c protocols

假设我定义了自己的协议(protocol)并将其命名为 NeighborNodeListener。 我有 NSMutableArray 来保存实现协议(protocol)的对象。 现在,我想遍历 NSMutalble 数组并为数组中的所有对象调用协议(protocol)中定义的方法之一。

 for(id <NeighborNodeListener> object in listeners){
      [object firstMethod];//first method is defined in the protocol 
 }

我正在考虑做一些这样的事情,但没有成功。 我想在 Objective C 中执行的代码在 Java 中看起来像这样

 List<NeighborNodeListener> listeners = new ArrayList<NeighborNodeListener>();
 Iterator<NeighborNodeListener> iter = listeners.iterator();
 while (iter.hasNext()) {
      iter.next().firstMethod();
 }

最佳答案

Objective-C 在类型方面不如 Java 严格,因此您需要在运行时进行检查。

请注意,下面的两个代码块做同样的事情——除了第一个检查 object 是否完全符合协议(protocol),而后者只检查你想调用的方法.

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"];
  }
}

关于objective-c - Objective-C ,关于遍历协议(protocol)变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5293453/

相关文章:

protocols - 什么是 SMPP 协议(protocol)?

objective-c - 上传视频时iOS 4.3崩溃

iphone - 如何重命名目录?

objective-c - 单击 NSTextField 下方

objective-c - NSTextView 的意外行为(因为没有标题栏的 NSWindow?)

objective-c - 使用 UIViewController 作为协议(protocol)

ios - SignificantLocationChanges 不适用于 iOS 8

xcode - 如何在 swift 中使用performSelector 的默认协议(protocol)实现?

python - 哪个标准异常类用于违反协议(protocol)?

ios - 使用 Swift 和委托(delegate)从 subview 更新父 View 上的标签