So I have 3 views as follows: viewController >> viewController2 >> viewController3.
In viewController3 I have created a Delegate Protocol. The protocol method is a simple method that prints out an NSLog.
When I call the delegates from ViewController3, only its parent (viewController2 ) responds not the (first) viewController. There are no errors.I think problem has got something to do with [v2 setDelegate:self]; in the viewController.m file.
Nevertheless,[self.v3 setDelegate:self]; works fine in ViewController2.m file.
Why does the (first) viewController delegate not respond ? Do delegates only work with its immediate child ??
> **ViewController.h**
#import <UIKit/UIKit.h>
#import "ViewController2.h"
#import "ViewController2.h"
@interface ViewController : UIViewController <PassData>{
ViewController2 *v2;
}
@property (strong, nonatomic) ViewController2 *v2;
> Blockquote
- (IBAction)button:(id)sender;
@end
> **ViewController.M**
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize v2;
- (IBAction)button:(id)sender {
v2 = [[ViewController2 alloc]initWithNibName:@"ViewController2" bundle:nil];
[v2 setDelegate:self];
[self.view addSubview:v2.view];
}
-(void)print: (BOOL)success;{
if (success == YES) {
NSLog(@"ViewController called");
}
}
@end
> > ViewController2.h
#import <UIKit/UIKit.h>
#import "ViewController3.h"
@interface ViewController2 : UIViewController <PassData> {
ViewController3 *v3;
}
@property (strong, nonatomic)ViewController3 *v3;
@property (retain) id delegate;
- (IBAction)button:(id)sender;
@end
ViewController2.m
#import "ViewController2.h"
@interface ViewController2 ()
@end
@implementation ViewController2
@synthesize v3,delegate;
- (IBAction)button:(id)sender {
v3 = [[ViewController3 alloc]initWithNibName:@"ViewController3" bundle:nil];
[self.v3 setDelegate:self];
[self.view addSubview:v3.view];
}
-(void)print: (BOOL)success;{
if (success == YES) {
NSLog(@"ViewController2 called");
}
}
@end
> ViewController3.h
#import <UIKit/UIKit.h>
@protocol PassData <NSObject>
@required
-(void)print:(BOOL)success;
@end
@interface ViewController3 : UIViewController {
id<PassData> delegate;
}
@property (retain) id delegate;
- (IBAction)callButton:(id)sender;
@end
ViewController3.m
#import "ViewController3.h"
@interface ViewController3 ()
@end
@implementation ViewController3
@synthesize delegate;
- (IBAction)callButton:(id)sender {
// call all delegates
[[self delegate]print:YES];
}
@end
v2 doesn’t have a method “print”, that’s a protocol method of v3 — you can’t chain delegate messages like this. If you want multiple controllers to respond to something in another controller, then you should use an NSNotification — any number of objects can register to receive a notification.