我知道这个问题已经在这里被询问和回答了很多次。但是我第一次处理这件事,仍然无法在脑海中完美实现它。这里的代码我有我实现的代理方法将SecondViewController
的数据传递给FirstViewController
。使用委托和协议在2个UIViewController之间传递数据
FirstViewController.h
#import "SecondViewController.h"
@interface FirstViewController : UITableViewController<sampleDelegate>
@end
FirstViewController.m
@interface FirstViewController()
// Array in which I want to store the data I get back from SecondViewController.
@property (nonatomic, copy) NSArray *sampleData;
@end
@implementation FirstViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SecondViewController *controller = [[SecondViewController alloc] init];
[self.navigationController pushViewController:controller animated:YES];
}
@end
SecondViewController.h
@protocol sampleDelegate <NSObject>
- (NSArray*)sendDataBackToFirstController;
@end
@interface SecondViewController : UITableViewController
@property (nonatomic, strong) id <sampleDelegate> sampleDelegateObject;
@end
SecondViewController.m
@interface SecondViewController()
@property (strong, nonatomic) NSArray *dataInSecondViewController;
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataInSecondViewController = [NSArray arrayWithObjects:@"Object1", @"Object2", nil];
}
- (NSArray*)sendDataBackToFirstController
{
return self.dataInSecondViewController;
}
@end
我是不是做正确吗?我希望它将self.dataInSecondViewController
中的数据发送到FirstViewController
,并将其保存在NSArray
属性sampleData
的FirstViewController
之上。
不知何故,我无法访问FirstViewController
中的sendDataBackToFirstController
。还有什么其他的东西想要在那里访问sendDataBackToFirstController
?
您需要设置第一个VC为代表第二个vc。所以第二个vc的委托方法需要在第一个vc中实现。然后在触发事件时从第二个vc调用该方法。从你的情况来看,如果你想拥有一个数据源或代表,你就不清楚了。如果使用第二个vc作为第一个vc的数据源,则它是第一个请求数据的vc。但是,当第二个vc发生某种事件时,它只是想返回第一个vc,然后是它的委托类型。然后,您需要将返回类型更改为void并将数据作为参数传递。 – Anupdas
正确。我试着在我的First vc的didSelectRow中做controller.delegate = self。但不知何故,控制器无法找到委托对象。我的代码到目前为止看起来是否正确? –
请按照@gdavis和艺术的答案 – Anupdas