没有调用委托方法,将委托设置为self?

时间:2014-06-15 19:03:03

标签: ios iphone objective-c delegates

所以我正试图让代理人使用,我到目前为止已经看过一些关于如何使用它们的教程。我仍然发现它们令人困惑,在尝试自己实施之后,遇到一个我似乎无法解决的问题。

我有两个ViewControllers,第一个ViewController包含UITextField *sampleTextField和一个方法switchViews的按钮。它还包含方法sendTextToViewController的协议声明。 SwitchViews也链接到切换到SecondViewController的segue。在SecondViewController中,唯一的对象是UILabel *outputLabel当用户点击按钮时,它会调用switchViews并且视图更改为SecondViewController,并且在加载outputLabel时应该更改为文本已在sampleTextField的{​​{1}}中输入。但是,永远不会调用委托方法ViewController。所有对象都在Interface Builder中创建。

以下代码使其更容易理解:

ViewController.h

sendTextToViewController

然后在 ViewController.m

中声明了这一点
#import <UIKit/UIKit.h>

@protocol TextDelegate <NSObject>

-(void)sendTextToViewController:(NSString *)stringText;

@end

@interface ViewController : UIViewController

- (IBAction)switchViews:(id)sender;

@property (weak, nonatomic) IBOutlet UITextField *sampleTextField;

@property (weak, nonatomic) id<TextDelegate>delegate;

@end

SecondViewController.h

- (IBAction)switchViews:(id)sender {
    NSLog(@"%@", self.sampleTextField.text);
    [self.delegate sendTextToViewController:self.sampleTextField.text];
}

SecondViewController.m

#import <UIKit/UIKit.h>
#import "ViewController.h"

@interface SecondViewController : UIViewController <TextDelegate>

@property (weak, nonatomic) IBOutlet UILabel *outputLabel;


@end

I've looked at this并且第一个答案是有道理的,但由于某种原因,它不起作用。

我认为问题出在我设置调用#import "SecondViewController.h" @interface SecondViewController () @end @implementation SecondViewController @synthesize outputLabel; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. ViewController *vc = [[ViewController alloc]init]; [vc setDelegate:self]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)sendTextToViewController:(NSString *)stringText { NSLog(@"Sent text to vc"); [outputLabel setText:stringText]; } 的地方,但不知道如何解决这个问题。一些正确方向的指针将非常感激。请记住,我是obj-c的新手,所以如果你能解释你在说什么,那就太棒了。谢谢。

2 个答案:

答案 0 :(得分:0)

您正在创建ViewController的新实例,但您不会对其执行任何操作。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    ViewController *vc = [[ViewController alloc]init];
    [vc setDelegate:self];
}

SecondViewController需要引用FirstViewController才能将自己设置为委托。

答案 1 :(得分:0)

首先,您不必使用委托来执行此类程序。 一种更简单的方法是在SecondViewController中创建一个属性,您可以将textField的内容传递给它。

您的代码无效,因为您在尚未设置的委托上调用了sendTextToViewController。您已将委托设置为ViewController的新实例,而不是屏幕上显示的实例。

相关问题