This is a slight follow on from a previous question:
for(id <stuffieProtocol> eachObject in stuffieArray) {
if([eachObject respondsToSelector:@selector(secretID)]) [eachObject secretID];
}
The above is a line from a fast enumeration loop that takes a number of objects out of an NSArray and checks to see if they respond to the method secretID. The method secretID is not part of the @protocol but rather a method defined on one of the objects in the collection.
The if statement above fails because the compiler says "No known instance method for selector secretID" Which is fine, id does not care and the method is not defined in <stuffieProtocol> I can fix this by casting each object to the type that does define secretID:
if([eachObject respondsToSelector:@selector(secretID)]) [(Ted *)eachObject secretID];
My question is in the original code, how does the compiler know that eachObject responds to the method secretID but yet when you ask it to call that method its says “No known method” I am just a little curious about the mechanics?
The compiler doesn’t know anything about whether the object responds to that selector but the runtime does. (i.e. The compiler doesn’t execute the code.) The compiler only cares that any NSObject can respond to
respondsToSelector:.