General Category > General Discussions

Multiple delegates?

(1/1)

rtamesis:
Let's say that ViewController B is a delegate of ViewController A. If I then create multiple subclasses of ViewController B, does that create a problem with having multiple delegates of ViewController A? From my understanding of protocols and delegates, there can only be one delegate for each class with a protocol or am I wrong?

kjmcneish:
Although most of the examples you see have just one delegate, you can absolutely have more than one. Rather than creating a single delegate property, you can create a collection of delegates. For example:


--- Code: ---@interface MyClass()

@property (nonatomic, strong, readwrite) NSMutableSet* delegates;

@end 

@implementation MyClass

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.delegates = [[NSMutableSet alloc] init];
}

- (void) addDelegate: (id<MyDelegateProtocol>) delegate
{
    [delegates addObject: delegate];
}

- (void) removeDelegate: (id<MyDelegateProtocol>) delegate
{
    [delegates removeObject: delegate];
}

@end
--- End code ---

All the best!
Kevin

Navigation

[0] Message Index

Go to full version