一种常见的方法是使用委托。由于 ViewController 应该尽可能独立,因此我们必须尽量减少它们之间的依赖关系。实际上,如果我理解正确,您对文件的想法也是如此。但是使用文件来组织 ViewController 之间的通信并不是很方便。通常你为你的第二个 ViewController 声明一个 @protocol SecondViewControllerDelegate (你点击一个“保存”按钮)。使用以下方法:
@protocol YourSecondViewControllerDelegate <NSObject>
-(void)yourSecondViewControllerDidCancel:(YourSecondViewController*)controller; //if you have a cancel button
-(void)yourSecondViewControllerDidFinish:(YourSecondViewController*)controller yourDataToReturn:(SomeData*)data andSomeMoreData:(AnotherDataType*)data2;
@end
然后将这样的属性添加到您的 SecondViewController:
@property (nonatomic, assign) id<YourSecondViewControllerDelegate> delegate; //Do not retain it!
然后你在 MainViewController 中采用你的协议。
@interface MainViewController()<YourSecondViewControllerDelegate> //you can do it in the private category to keep the class interface clear.
@end
@implementation
//don't forget to implement those methods here :)
@end
当您从 MainViewController 触发 segue 时,您可以将 MainViewController 设置为 SecondViewController 的委托:
SecondViewController *destinationController = [[SecondViewController alloc] init]; //Just for example.
destinationController.delegate = self;
//trigger a segue :)
当用户按下 SecondViewController 中的 Save 按钮时,您调用委托的 yourSecondViewControllerDidFinish:
[self.delegate yourSecondViewControllerDidFinish: self yourDataToReturn: someData andSomeMoreDate: someMoreData];
这样 MainController 的 yourSecondViewControllerDidFinish 方法就会被调用。你可以在那里选择 someData 和 someMoreData 。
您可以在本教程中获得有关它的更多详细信息:
Apple's your second iOS app tutorial