Task C, Question of iteration through protocol variables

Say I defined my own protocol and named it NeighborNodeListener. And I have an NSMutableArray that contains objects that implement the protocol. Now I want to iterate through the NSMutalble array and call one of the methods defined in the protocol for all objects in the array.

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

I was thinking of doing something like this, but that didn't work. The code I want to do in Objective-C will look like this in Java

  List<NeighborNodeListener> listeners = new ArrayList<NeighborNodeListener>(); Iterator<NeighborNodeListener> iter = listeners.iterator(); while (iter.hasNext()) { iter.next().firstMethod(); } 
+4
source share
1 answer

Objective-C is a little less strict than Java in terms of input, so you will need to check it at runtime.

Note that the two code below does the exact same thing, except that the former checked the object for full compliance with the protocol, while the latter simply checks the method you want to call.

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

Or,

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

Source: https://habr.com/ru/post/1343563/


All Articles