我正在尝试在两个视图控制器之间传递数据。viewcontroller2 是 viewcontroller 的代表.. 注意.. 我称委托属性为“homie”是的,我知道这是不好的做法,但我只是在试图理解这个概念。
这是视图控制器:
#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
在 viewdidload 中,我实例化了第一个视图控制器,并将自己设置为它的代表。我假设当 viewcontroller2 在其方法中运行代码时,它将查看其委托是否已实现委托方法并使用该代码..我在这里缺少什么?