Objective c 如何在两个不同的UIViewController之间使用iAction进行委托

Objective c 如何在两个不同的UIViewController之间使用iAction进行委托,objective-c,delegates,protocols,ibaction,delegation,Objective C,Delegates,Protocols,Ibaction,Delegation,我只是想了解委托人是如何工作的,我遇到了麻烦 我有两个类UIViewController都连接到故事板中,第一个类ViewController.h/m包含一个带有单元格的TableView,第二个类AddNameViewController.h/m只包含一个我想要写入的文本字段和一个按钮Add Name 正如您所理解的,我希望按下按钮将写入文本字段的内容发送到TableView,非常简单 由于我有两个不同的控制器和一个数组,其中包含tableview保存的数据,所以我想用一个委托将它们连接起来,

我只是想了解委托人是如何工作的,我遇到了麻烦

我有两个类UIViewController都连接到故事板中,第一个类ViewController.h/m包含一个带有单元格的TableView,第二个类AddNameViewController.h/m只包含一个我想要写入的文本字段和一个按钮Add Name

正如您所理解的,我希望按下按钮将写入文本字段的内容发送到TableView,非常简单

由于我有两个不同的控制器和一个数组,其中包含tableview保存的数据,所以我想用一个委托将它们连接起来,以便了解它

下面是一些代码:

ViewController.h

#import "AddNameViewController.h"
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, AddNameViewControllerDelegate>
@property (strong, nonatomic) NSMutableArray *array;
@end
@protocol AddNameViewControllerDelegate <NSObject>

-(void)addStringWithString:(NSString*)string;

@end

@interface AddNameViewController : UIViewController

@property (weak, nonatomic) id <AddNameViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UITextField *myTextField;

-(IBAction)add:(id)sender;

@end
AddNameViewController.h

#import "AddNameViewController.h"
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, AddNameViewControllerDelegate>
@property (strong, nonatomic) NSMutableArray *array;
@end
@protocol AddNameViewControllerDelegate <NSObject>

-(void)addStringWithString:(NSString*)string;

@end

@interface AddNameViewController : UIViewController

@property (weak, nonatomic) id <AddNameViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UITextField *myTextField;

-(IBAction)add:(id)sender;

@end
数组初始化正确,没有错误,没有警告,没有崩溃,只是看起来方法addStringWithString甚至没有被调用,因为它甚至没有NSLog任何东西


很明显,故事板、方法和出口中的所有内容都已连接,感谢您的帮助。

在AddNameViewController的界面生成器中,您是否将内部的按钮事件润色连接到了action-IBActionadd:idsender

也试试这个

-(IBAction)add:(id)sender
{
 if([self.delegate respondsToSelector:@selector(addStringWithString:)]) {
[self.delegate addStringWithString:self.myTextField.text];
}
// I've also tried with this but nothing --> [self.delegate addStringWithString:@"aa"];
}

是的,按钮事件连接到故事板内部的润色,使用正确的方法IBActionadd:idsender,显然是连接到AddNameViewController,我也尝试了您提到的if语句,但没有发生任何事情我已经在if语句中添加了NSLog,并且没有打印任何内容,所以代理没有响应该选择器,不知道为什么…首先启动哪个viewcontroller,viewcontroller还是AddNameViewController,因为如果AddNameViewController是第一个,它的代理永远不会初始化,NSLogself.delegate是nilViewController是第一个,如果我添加[anvc nameMethod];在ViewController的viewDiDLoad中调用了该方法,因此委托被初始化,但我想通过触摸按钮来调用该方法,而不是在viewDiDLoad中,似乎委托被初始化并随后被解除分配,这就是为什么我添加[anvc method];加载到viewdidload它可以工作,否则就不行了,我不知道为什么会取消分配。。