I’m new to the Objective C business (Java developer most of the time) and am woking on my first killer app now. 🙂
At the moment I am somehow confused about the usage of selectors as method arguments. They seem to be a little bit different than delegates in C# for example.
Given the following method signature
-(void)execute:(SEL)callback;
is there a way to enforce the signature for the selector passed to such a method?
The method is expecting a selector of a method with the following signature
-(void)foo:(NSData*)data;
But the SEL (type) is generic, so there is a good chance to pass a wrong selector to the
execute method. OK at least at runtime one would see a funny behavior… but I would like to see a compiler warning/error when this happens.
The quick answer is: no, there is no way to have the compiler enforce the method signature of a method selector that is provided via a
SELargument.One of the strengths of Objective-C is that it is weakly-typed language, which allows for a lot more dynamic behaviour. Of course, this comes at the cost of compile-time type safety.
In order to do what (I think) you want, the best approach is to use delegates. Cocoa uses delegates to allow another class to implement “callback”-type methods. Here is how it might look:
Using the
@requiredkeyword in your delegate protocol will prevent you from assigning a delegate to aFooControllerthat does not implement the method exactly as described in the protocol. Attempting to provide a delegate that does not match the@requiredprotocol method will result in a compiler error.Here is how you would create a delegate class to work with the above code:
And here is how you would use everything: