3 ms·
It's not just explicit @protocols. Everything in Objective-C is under an implicit protocol: the code itself. Even if a method says it requires an argument of ty
by alextgordon 16y ago
It's not just explicit @protocols. Everything in Objective-C is under an implicit protocol: the code itself. Even if a method says it requires an argument of type Foo, you can usually substitute an object of type Bar, so long as Bar responds to all the messages that the method could send to Foo.
For example
- (void)printValue:(Foo *)foo {
NSLog(@"%@", [foo stringValue]);
}
it doesn't matter that printValue: says it wants a Foo, you can still pass it an NSTextField all the same.
This gets really fun when you start using -respondToSelector: Now we can do:
- (void)printValue:(Foo *)foo {
if ([foo respondsToSelector:@selector(stringValue)])
NSLog(@"%@", [foo stringValue]);
}
This sort of thing is used throughout Cocoa (although these days explicit protocols are replacing it). It's difficult to do in C++, which is one of the reasons why C++ UI toolkits are so cumbersome.