Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 978
Mark Avatar asked Mar 06 '13 23:03

Mark


1 Answers

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.

like image 149
CodaFi Avatar answered Sep 22 '22 21:09

CodaFi