Objective-C: How to pass an object as a block argument to a method that expects its base class?
objective-c, objective-c-blocks
Solution
Unfortunately, this is a limitation of the Blocks API. If you'd like to, you have the option of completely forgoing type safety and declaring the block as:
+(void) doSomething:(void (^)(id)) obj;
Which allows you to set the class of the arguments of the block. But again, this is completely unsafe, type-wise.
Problem
If I have the following objects: ``` @interface Simple : NSObject @end @interface Complex : Simple @end ``` And another object like: ``` @interface Test : NSObject +(void) doSomething:(void (^)(Simple*)) obj; @end ``` Everything works if I call the method like: ``` [Test doSomething:^(Simple * obj) { }]; ``` When I try instead to call it like: ``` [Test doSomething:^(Complex * obj) { }]; ``` The compiler says that: `Incompatible block pointer types sending 'void (^)(Complex *__strong)' to parameter of type 'void (^)(Simple *__strong)'` Because `Complex` extends `Simple`, I thought this would work, like in Java. Is there a way to achieve this somehow?