Question

Maybe I misunderstand the delegate pattern, but can somebody please explain how can I get delegate calls into 2 classes from a single one when I only define one protocol and delegate property?

Running the code below will only call doSomething in the detail2VC, but I want to have the message in both. I can define second property that would conform with the protocol, or define second protocol, but I assume that's not the right approach.

ViewController.h

#import <UIKit/UIKit.h>

@protocol ViewControllerDelegate <NSObject>

@optional
- (void)doSomething;

@end

@interface ViewController : UIViewController

@property (nonatomic, weak) id <ViewControllerDelegate> delegate;

@end

ViewController.m

#import "ViewController.h"
#import "Detail1VC.h"
#import "Detail2VC.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ([self.delegate respondsToSelector:@selector(doSomething)]) {

        [self.delegate doSomething];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"d1"]) {

        self.delegate = (Detail1VC *)segue.destinationViewController;
    }

    if ([segue.identifier isEqualToString:@"d2"]) {

        self.delegate = (Detail2VC *)segue.destinationViewController;
    }
}

@end

Detail1VC.h

#import <UIKit/UIKit.h>
#import "ViewController.h"

@interface Detail1VC : UIViewController <ViewControllerDelegate>

@end

Detail1VC.m

#import "Detail1VC.h"

@interface Detail1VC ()

@end

@implementation Detail1VC

- (void)doSomething
{
    NSLog(@"detail1 done");
}

@end

Detail2.VC is identical to Detail1.VC

Was it helpful?

Solution 2

Use the best practice, by using only one delegate and change it dynamically form outside the class who declared the protocol. Code reviewers can hate the way you have NSArray of delegates, or can be misleading for other developers if you work with a team.
The best approach is to use NSNotification to notify multiple objects about an event. Keep using the best code, which is familiar to other objective-c developers.

OTHER TIPS

Just have a collection of delegates instead of just one. All of them should conform to the same protocol of course.

In your master instance you just have to iterate through your collection (NSSet or NSArray) of delegates and call the method declared in your protocol.

There is no rule that forbids to do that.

Of course you could also think if other patterns would not fit better like observer or why not simply use the NSNotificationCenter.

Nothing is bad just pick up what fits you the best.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top