Mark
Mark

Reputation: 69920

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?

Upvotes: 7

Views: 1296

Answers (2)

CodaFi
CodaFi

Reputation: 43330

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.

Upvotes: 8

Jack Lawrence
Jack Lawrence

Reputation: 10772

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

Upvotes: 2

Related Questions