2012-06-19 56 views
0

我試圖從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我失去了一些東西?在此先感謝

+0

嘗試將VCA.h中的屬性類型更改爲(非原子)? – achi

+0

另外,請確保IB完全連接起來。 – achi

+0

我用故事板和一切都鏈接起來。試着改變屬性類型nonatomic但沒有結果。 –

回答

1

您使用故事板?如果是的話,你只需按錯鍵:故事板自身的初始化視圖控制器,所以你的代碼:

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

只設置委託一些未使用的視圖控制器上。 使用segues,不要嘗試重新發明輪子。

+0

其實我想學習如何使用代表而不使用segues.thats爲什麼我發佈它。以及使用代表做什麼解決方案? –

+0

您需要對現有視圖的引用。也許你可以在這裏使用'superview',但我不確定這是一個好的解決方案。 通常,您不需要參考由故事板初始化的實例。這只是使用委託模式的一個壞例子。 – folex