调用其他类的委托方法

时间:2014-10-15 17:37:12

标签: ios class methods action delegation

我阅读了不同的委托方法帖子,但我仍然无法弄清楚出了什么问题。

我想从我的主ViewController(称为 mainVC )显示一个自定义弹出窗口(一个xib文件及其关联的弹出窗口控制器,名为 popoverVC )。在我的弹出窗口中有一个按钮,用于在mainVC内的文本字段中显示文本。我的问题如下:

  • 方法" firstMethod:"在xib文件中由我的按钮调用的popoverVC正在工作( NSLog消息"调用firstMethod!"显示在控制台上
  • 这种方法&#34; firstMethod&#34;调用另一种方法&#34; secondMethod&#34;位于mainVC。此方法在popoverVC内部的协议声明中定义,并且也在工作中(在控制台上: NSLog消息&#34; secondMethod Called!&#34;除了之前的&#34; firstMethod Called&#34; < / em>的)。

我不明白的是,我在 mainVC 的第二种方法中添加了一个代码行,以在textField中显示文本(同样在 mainVC 中)这不起作用(虽然NSLog命令的上一行正在运行)。

我觉得因为我正在创建 mainVC 的新实例来调用 popoverVC 中的第二个方法,所以我指的是一个不同于 popoverVC 的文本字段出现在 mainVC 一开始就调用 popoverVC 。由于NSLog只在控制台中显示,因此我在不同的视图控制器上。

我担心我的解释不太清楚......以防我在下面添加我的代码。

(在mainVC中使用 textfield beginEditing 调用我的xib文件(及其popoverVC类)

popoverVC.h:

@protocol mainVCDelegate <NSObject>

@optional
- (void)insertValue;
@end

#import...

popoverVC.m:

//method called by the button in Xib file and supposed to call the method in mainVC to then display text inside a textfield in mainVC

- (IBAction)updateTextFieldInMainVC:(id)sender {

    NSLog(@"firstMethod called!");

    mainVC *mvc = [[mainVC alloc] init];
    [mvc insertValue];
    }

mainVC.h:

@interface mainVC : UIViewController <mainVCDelegate>

mainVC.m:

- (void)insertValue {

 NSLog(@"secondMethod called!"); ---> this is displayed on the console

self.textfield.text = @"sometext"; ---> this is not displayed in the textfield

}

1 个答案:

答案 0 :(得分:2)

看起来你错过了关于授权的重要部分。我建议在代表团上阅读Apple's guide。但与此同时,这就是你所缺少的。

委托允许popoverVC不知道mainVC。您正在创建mainVC的实例并直接调用它的方法insertValue,这不是委托。

在popoverVC.h

@protocol mainVCDelegate <NSObject>

@optional
- (void)insertValue;
@end

@interface popoverVC : UIViewController

@property (weak) id <mainVCDelegate> delegate;

@end

在popoverVC.m

- (IBAction)updateTextFieldInMainVC:(id)sender {
    NSLog(@"firstMethod called!");
    if ([delegate respondsToSelector:@selector(insertValue)]) {
        [delegate insertValue];
    }
}

在mainVC.h中

@interface mainVC : UIViewController <mainVCDelegate>

在mainVC.m

// In init/viewDidLoad/etc.
popoverVC *popover = [[popoverVC alloc] init];
popover.delegate = self;  // Set mainVC as the delegate

- (void)insertValue {
    NSLog(@"secondMethod called!"); 
    self.textfield.text = @"sometext";
}