所以我有3个视图如下:viewController >> viewController2 >> viewController3。在 viewController3 中,我创建了一个委托协议。协议方法是打印出 NSLog 的简单方法。
当我从 ViewController3 调用委托时,只有其父 (viewController2) 不响应(第一个)viewController。没有错误。我认为问题与 [v2 setDelegate:self]; 在 viewController.m 文件中。尽管如此,[self.v3 setDelegate:self]; 在 ViewController2.m 文件中工作正常。
为什么(第一个)viewController 委托没有响应?代表只与它的直系孩子一起工作吗?
> **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