我想在兩個視圖控制器之間傳遞數據。 viewcontroller2是viewcontroller的一個委託.. note ..我叫委託屬性「homie」是的,我知道這是不好的做法,但我只是在試圖理解這個概念。試圖學習Objective-C的代表。爲什麼我的示例項目不工作?
這裏是視圖 - 控制:
#import <UIKit/UIKit.h>
@protocol ViewControllerDelegate <NSObject>
@required
- (void)sendData:(NSString *)theString;
@end
@interface ViewController : UIViewController
@property (nonatomic, assign) id <ViewControllerDelegate> homie;
- (void)doSomething;
- (IBAction)doneText:(id)sender;
@end
實現:
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)doSomething{
}
- (IBAction)doneText:(id)sender {
UITextField *thisField = sender;
if([_homie respondsToSelector:@selector(sendData:)]){
[_homie sendData:[thisField text]];
}
}
現在這裏是實施第一
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface ViewController2 : UIViewController <ViewControllerDelegate>
- (IBAction)hittingbtn:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *textfield;
@property (strong, nonatomic) ViewController *vc;
@end
執行其他視圖控制器:
#import "ViewController2.h"
@interface ViewController2()
@end
@implementation ViewController2
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
ViewController *theview = [[ViewController alloc]init];
theview.homie = self;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// DELEGATE METHOD
- (void)sendData:(NSString *)theString{
[_textfield setText:theString];
}
- (IBAction)hittingbtn:(id)sender {
}
@end
in viewdidload我實例化第一個viewcontroller,並將自己設置爲它的委託。即時假設然後當viewcontroller2在其方法中運行代碼,然後它會看到它的委託是否實現了委託方法並使用該代碼..我在這裏失蹤了什麼?
可以調試'送出數據:'看方法,如果它被稱爲?通過放置一個斷點,或者插入一個'NSLog()'語句? –
它不被稱爲 – hamobi
我認爲問題是你的ViewController的alloc init正在創建一個不同於你在屏幕上的實例。你如何把ViewController放在屏幕上? – rdelmar