Callback request using selectors

How do I declare a class that has a method / message that accepts a selector, stores the value of the selector and then calls the selector later?

those. if its named SomeObject

it will be called like this:

-(id) init {
    // normal stuff here
    o = [[SomeObject alloc] init];
    return self;
}

-(void) checkSomething {
    [o checkSomethingWithResponse: @selector(answer:)]
}

-(void) answer: (int) value {
    NSLog(@"Check complete: %d", value);
}

      

(Sorry, I know it might be RTFM, but I can't find any information)

+2


source to share


1 answer


The class SomeObject

requires a reference to the object to be sent messages.

This is pretty accurate a delegate pattern; look at the implementation details.

(Note that the delegate pattern is generally not required for all delegate methods. In this case, if -answer is required: it looks more like a UITableViewDataSource or NSTableView datasource, for example. The implementation is the same as the delegate pattern implementation, you just don't need check if an object implements this method).

Or, if you really want an integer value in the target / action (in Cocoa parlance) pairs:

I suggest redeclaring -answer: as:

- (void) answer: (NSNumber *) aValue;

      

This avoids having to deal with an argument other than an object.



In your SomeObject class, you have something like:

[myAnswerer performSelector: myAnswererSelector withObject: [NSNumber numberWithInt: 1]];

      

And you can even declare myAnswerer and myAnswererSelector as:

@property(retain) MyAnswererClass *myAnswerer;
@property SEL myAnswererSelector;

      

Then use @synthesize in SomeObject implementation to synthesize setter / getter.

Note that on SnowLeopard, all of this can be addressed much more broadly with blocks ...

+6


source







All Articles