Objective-C: How to pass an object as a block argument to a method that expects its base class?

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 as follows:

 [Test doSomething:^(Simple * obj) { }]; 

When I try to call it instead:

 [Test doSomething:^(Complex * obj) { }]; 

The compiler says that:

Incompatible block pointer types sending 'void (^)(Complex *__strong)' to parameter of type 'void (^)(Simple *__strong)'

Since Complex extends Simple , I thought it would work, as in Java.

Is there any way to achieve this somehow?

+7
source share
2 answers

Unfortunately, this is a limitation of the API Blocks. If you want, you have the opportunity to completely abandon type safety and declare a block as:

 +(void) doSomething:(void (^)(id)) obj; 

This allows you to set the block argument class. But then again, this is completely unsafe , by type.

+8
source

Use id instead of Complex * or Simple * . Block parameter types are handled differently than method parameter types (thanks @CodaFi)

+2
source

All Articles