我正在尝试使用委托将viewControllerA中的简单数据发送到viewControllerB,但无法在我的代码中找到问题。这是代码
ViewControllerA.h
中的
#import <UIKit/UIKit.h>
@class ViewControllerA;
@protocol viewControllerADelegate <NSObject>
-(void) addItem: (ViewControllerA *)controller data:(NSString *)item;
@end
@interface ViewControllerA : UIViewController
- (IBAction)buttonPressed:(id)sender;
@property (assign) id<viewControllerADelegate> delegate;
@end
在ViewControllerA.m
#import "ViewControllerA.h"
@interface ViewControllerA ()
@end
@implementation ViewControllerA
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)buttonPressed:(id)sender {
[self.delegate addItem:self data:@"this is data"];
}
@end
这里是ViewControllerB.h
#import <UIKit/UIKit.h>
#import "ViewControllerA.h"
@interface ViewControllerB : UIViewController<viewControllerADelegate>
@end
和ViewControllerB.m
#import "ViewControllerB.h"
#import "ViewControllerA.h"
@interface ViewControllerB ()
@end
@implementation ViewControllerB
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
ViewControllerA *vba = [[ViewControllerA alloc]init];
[vba setDelegate:self];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) addItem: (ViewControllerA *)controller data:(NSString *)item{
NSLog(@"delegate function called");
}
@end
从未调用已实现的函数-(void) addItem: (ViewControllerA *)controller data:(NSString *)item
。我遗漏了什么?提前致谢
答案 0 :(得分:1)
你在使用故事板吗?如果是的话,你只需按错了按钮:storyboard自己初始化视图控制器,所以你的代码:
ViewControllerA *vba = [[ViewControllerA alloc]init];
[vba setDelegate:self];
在一些未使用的视图控制器上设置委托。 使用segues,不要试图重新发明轮子。