Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>SEL</code> argument.</p> <p>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.</p> <p>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:</p> <blockquote> <p><strong>FooController.h</strong></p> </blockquote> <pre><code>@protocol FooControllerDelegate @required: - (void)handleData:(NSData *)data forFoo:(FooController *)foo; @end @interface FooController : NSObject { id &lt;FooControllerDelegate&gt; * delegate; } @property (assign) id &lt;FooControllerDelegate&gt; * delegate; - (void)doStuff; @end </code></pre> <blockquote> <p><strong>FooController.m</strong></p> </blockquote> <pre><code>@interface FooController (delegateCalls) - (void)handleData:(NSData *)data; @end @implementation FooController @synthesize delegate; - (id)init { if ((self = [super init]) == nil) { return nil; } delegate = nil; ... return self; } - (void)doStuff { ... [self handleData:data]; } - (void)handleData:(NSData *)data { if (delegate != nil) { [delegate handleData:data forFoo:self]; } else { return; // or throw an error // or handle it yourself } } @end </code></pre> <p>Using the <code>@required</code> keyword in your delegate protocol will prevent you from assigning a delegate to a <code>FooController</code> that does not implement the method exactly as described in the protocol. Attempting to provide a delegate that does not match the <code>@required</code> protocol method will result in a compiler error.</p> <p>Here is how you would create a delegate class to work with the above code:</p> <pre><code>@interface MyFooHandler &lt;FooControllerDelegate&gt; : NSObject { } - (void)handleData:(NSData *)data forFoo:(FooController *)foo; @end @implementation MyFooHandler - (void)handleData:(NSData *)data forFoo:(FooController *)foo { // do something here } @end </code></pre> <p>And here is how you would use everything:</p> <pre><code>FooController * foo = [[FooController alloc] init]; MyFooHandler * fooHandler = [[MyFooHandler alloc] init]; ... [foo setDelegate:fooHandler]; // this would cause a compiler error if fooHandler // did not implement the protocol properly ... [foo doStuff]; // this will call the delegate method on fooHandler ... [fooHandler release]; [foo release]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload