【问题标题】:how does this set delegate method work?这个设置委托方法是如何工作的?
【发布时间】:2025-11-26 16:30:01
【问题描述】:

这些是我在子视图控制器中的委托方法。

@protocol assignNames<NSObject>

-(void)setFirstName:(NSString*)firstName;
-(void)setLastName:(NSString*)lastName;

@end`

在我的父视图控制器中,我在文本字段中收到名字。 这是我的代码的一部分。

VIEWCONTROLLER.M

\\ FirstName is the name of my textField string


viewcontroller2 *viewc = [[viewcontroller2 alloc]init];
viewc2 = [segue destinationViewController];
viewc2.FNT = FirstName.text;   

[viewc2 setDelegate:self ]; \\ Here is my question

那么,当我给出这个方法时,它究竟意味着什么??因为如果我将它包含在我的代码中似乎什么都不会发生。

【问题讨论】:

  • viewcontroller2 *viewc = [[viewcontroller2 alloc]init]; viewc2 = [segue destinationViewController]; 应改为viewcontroller2 *viewc = [segue destinationViewController];
  • 是的,第一行是不需要的。

标签: ios objective-c uiviewcontroller delegates


【解决方案1】:

childviewController 中的@protocol 块是childviewController 的委托应实现的方法列表。当您从viewController.m 调用[viewc2 setDelegate:self ] 时,您的viewController 将成为您的childViewController 的代表。

那么所有这些步骤的作用是什么?嗯,首先,因为父 VC 订阅了assignNames 委托,所以它将实现这两​​个方法。其次,子 VC 可以像这样调用父 VC 中的协议方法:

[self.delegate setFirstName:@"Derp"];
// we are in the child VC and the delegate would be parent VC

总之,曾经有一段时间,这一切都让我感到困惑,所以我知道它是怎么回事。我建议你通过一些教程来掌握这些东西,比如this one here

【讨论】:

  • 谢谢。这是一个有用的链接。