我試圖從viewControllerA發送簡單的數據使用委託viewControllerB卻找不到我code.here問題從controllerA將數據傳遞到controllerB是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
是從來沒有called.Am我失去了一些東西?在此先感謝
嘗試將VCA.h中的屬性類型更改爲(非原子)? – achi
另外,請確保IB完全連接起來。 – achi
我用故事板和一切都鏈接起來。試着改變屬性類型nonatomic但沒有結果。 –