Search code examples
objective-c-blocks

Property referring to a common interface for two Blocks


I have a class Request that should have a Callback-block property, lets call it RequestCallback.

The request itself shouldn't be used, but it has two subclasses. APIRequest and HttpRequest. (yes, in this case there is a difference).

The callback blocks are different for APIRequest and HttpRequest, lets call them APIRequestCallback and HttpRequestCallback.

Block definitions:

typedef void (^HttpRequestCallback)(HttpResponse *);
typedef void (^APIRequestCallback)(APIResponse *);

I haven't found any way to let my Request class have one Callback property, which can be of either APIRequestCallback or HttpRequestCallback type.

I can think of ways this can be done, but I haven't seen anything implying it. Examples would be storing my Callback object as id, Letting APIRequestCallback and HttpRequestCallback extend a defined RequestCallback etc.

// Can be either HttpRequestCallback or APIRequestCallback
@property (copy) RequestCallback callback;
// or
@property (strong) id callback;
// or
@property (strong) id <RequestCallback> callback;

Does some skilled objective C developer have a solution to this?


Solution

  • I have found a working solution that pleases me for now. If someone knows better, please educate me.

    The Request class uses the following Block typedef:

    typedef void (^RequestCallback)(id);
    

    And uses a property like this:

    @property (copy) RequestCallback callback;
    

    This works because the id type doesn't distinguish between APIResponse objects and HttpResponse objects. I would love to use Objective C's new Generics syntax to force the type to be a __covariant of Response but I couldn't get it to work.