Objective-C type-check a block?

ios, objective-c, objective-c-blocks

Solution

Frankly, if the callbacks have different types, they should be under different keys. Why not use the keys `@"callbackWithOneParam"` and `@"callbackWithTwoParams"`? To me, that's superior to having a generic "callback" key plus a separate "type" key to tell you how to interpret the callback.

But what this really calls for is to use objects of custom classes instead of dictionaries. You've crossed the boundary where generic objects stop being convenient and start to cause more problems than they solve.

Problem

This is different from other "can I check the type of a block" posts on SO, as far as I can tell anyway. I want to know if, given a block object of unknown signature, I can learn what arguments it accepts prior to invoking? I have a situation where I have a number of callbacks associated with objects in a dictionary. I want some of those callbacks to expect a different set of arguments. The example here is extremely simplified, but I think it gets the point across. How can I find out if a block is of a type I previously typedef'd? ``` //MyClass.m // I start by declare two block types typedef void (^callbackWithOneParam)(NSString*); typedef void (^callbackWithTwoParams)(NSString*, NSObject*); ........ // I create a dictionary mapping objects to callback blocks self.dict = @{ @"name": "Foo", @"callback": ^(NSString *aString) { // do stuff with string } }, { @"name": "Bar", @"callback": ^(NSString *aString, NSObject *anObject) { // do stuff with string AND object } } ..... // Later, this method is called. // It looks up the "name" parameter in our dictionary, // and invokes the associated callback accordingly. -(void) invokeCallbackForName:(NSString*)name { // What is the type of the result of this expression? [self.dict objectForKey: name] // I want to say: (pseudocode) thecallback = [self.dict objectForKey: name]; if (thecallback is of type "callbackWithOneParam") { thecallback(@"some param") } else if (thecallback is of type "callbackWithTwoParams") { thecallback(@"some param", [[NSObject alloc] init]); } } ```

Original source