0

我正在尝试使用委托将简单数据从 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永远不会被调用。我错过了什么吗?提前致谢

4

1 回答 1

1

你在使用故事板吗?如果是,你只是按错了按钮:故事板自己初始化视图控制器,所以你的代码:

ViewControllerA *vba = [[ViewControllerA alloc]init];
[vba setDelegate:self];

只是在一些未使用的视图控制器上设置委托。使用segues,不要试图重新发明轮子。

于 2012-06-19T19:05:20.440 回答