您可以让 SecondViewController 成为 FirstViewController 的一个属性。这样 FirstViewController 可以引用它。
编辑回答评论中的问题
属性示例:
@interface FirstViewController()
property (strong, nonatomic) SecondViewController *secondViewController;
@end
@implementation FirstViewController
-(id)init
{
if (self = [super init]) {
self.secondViewController = [[SecondViewController alloc] init];
}
return self;
}
-(void)didPressBanana
{
[self.secondViewController bananaWasPressed];
// OR
self.secondViewController.fruit = @"banana";
}
@end
SecondViewController.h
@interface SecondViewController
@property (strong, nonatomic) NSString *fruit;
@end
或者
第二视图控制器.m
-(void)bananaWasPressed
{
self.fruit = @"banana";
}
或者,如果您希望采用另一种方式并让 SecondViewController 与 FirstViewController 通信,则可以使用协议。
协议示例:
SecondViewController.h
@protocol SecondViewControllerDelegate
-(void)didPressBanana;
@end
@interface SecondViewController : UIViewController
@property (nonatomic, unsafe_unretained) id<SecondViewControllerDelegate> delegate;
@end
第二视图控制器.m
-(void)didPressBanana
{
[self.delegate didPressBanana];
}
第一视图控制器.m
@interface FirstViewController()
@property (nonatomic, strong) SecondViewController *secondViewController;
@end
@implementation FirstViewController <SecondViewControllerDelegate>
-(id)init
{
if (self = [super init]) {
self.secondViewController = [[SecondViewController alloc] init];
}
return self;
}
-(void)viewDidLoad
{
[self.secondViewController setDelegate:self];
}
// delegate method conforms to SecondViewControllerDelegate protocol
-(void)didPressBanana
{
// do something
}
@end