Volchik
Volchik

Reputation: 309

How to implement two delegates of the same type in one class?

I am looking for good pattern for such a situation. Let's we have class with delegate:

@protocol MyDelegate
-(void) someEvent;
@end

@interface MyServiceClass
@property (nonatomic,weak) id<MyDelegate> delegate;
@end

And we have two instances of this class. For example serviceObject1 and serviceObject2. Now in our controller we want to receive events from both of instances:

-(void) registerDelegates {
    serviceObject1.delegate=self;
    serviceObject2.delegate=self;
}

-(void) someEvent {
  // do something
}

All is good except that events from both instances will be thrown to one someEvent method. For me will be more comfortable to separate events from serviceClass1 and serviceClass2 to different methods.

I saw three approaches but does not like any of them:

  1. Send instance of caller as argument of someEvent and check from which instance this event is and redirect to appropriate method.
  2. Create two fake objects in my controller and register them as delegates to service1Class. And from this objects call different methods in my controller.
  3. Use anonymous blocks instead of delegates. Good decision but i don't know how to unregister them.

May be exists another solution that i missed?

Upvotes: 1

Views: 619

Answers (1)

Chris C
Chris C

Reputation: 3251

The way this is handled is by passing the MyServiceClass instance as one of the method parameters, basically what you wrote for #1.

That's how Apple does it and it's kind of standard practice.

@protocol MyDelegate
-(void) someEventFromService:(MyServiceClass *serviceClass);
@end

Upvotes: 3

Related Questions