Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a subclass add parameters in a block in a parameter in an inherited method?

The situation

A superclass defines a method and a subclass redefines that method. The only difference is that the subclass adds a parameter in a block, which itself is a parameter of the method.

An example

Imagine I have a class Collection and a descendant class List, which define—among other methods—an enumeration method in NSArray-style.

@interface Collection : NSObject
- (void)enumerateObjectsUsingBlock: (void (^)(id obj))block;
@end

@interface List : Collection
- (void)enumerateObjectsUsingBlock: (void (^)(id obj, int index))block;
@end

The question

Does this work (on all platforms) and does it conform with standards?

I would imagine it would work since the parameter list in the superclass method isn’t affected, while users of the subclass method would be aware (optionally with some type-casting) of the extra parameter.

like image 885
Constantino Tsarouhas Avatar asked Mar 21 '23 05:03

Constantino Tsarouhas


1 Answers

In short; no, don't do this.

Longer:

It'll work in most situations, but you'll have to strive to avoid compiler warnings. Objective-C does not support co-variant or contra-variant declarations of methods (which was why instancetype was created). Since the block types are different, the method argument types are different.

Nor can you assume that a functions, blocks or methods that take, say, (a), (a,b), (a,b.c), (a,b,c,d), etc... will be compatible at call site. I.e. you can't say fun(a,b,c,d) where fun is actually fun(a) and be guaranteed that you'll get what you expect.

like image 191
bbum Avatar answered Apr 05 '23 23:04

bbum