你不需要使用 NSNotificationCenter、NSUserDefaults 或全局变量。
只要视图控制器是相关的(并且查看 OP 的问题,它们肯定是相关的),您可以简单地设置视图控制器以保持对彼此的引用(其中一个引用当然是弱的,以便避免“保留”或“强参考”循环)。然后每个视图控制器可以根据需要在另一个视图控制器上设置属性。示例如下...
注意:这个概念适用于任何两个相关的视图控制器。但是,以下代码假定:
- 有问题的视图控制器通过导航控制器相关联,第二个视图控制器通过 push segue 连接到第一个视图控制器。
- 正在使用 iOS 5.0 或更高版本(因为它使用情节提要)。
第一视图控制器.h
@interface FirstViewController : UIViewController
/* Hold the boolean value (or whatever value should be
set by the second view controller) in a publicly
visible property */
@property (nonatomic, assign) BOOL someBooleanValue;
/* Provide a method for the second view controller to
request the first view controller to dismiss it */
- (void)dismissSecondViewController;
@end
第一视图控制器.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation FirstViewController
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
/* Get the reference to the second view controller and set
the appropriate property so that the secondViewController
now has a way of talking to the firstViewController */
SecondViewController *vc = [segue destinationViewController];
vc.firstViewController = self;
}
- (void)dismissSecondViewController
{
// Hide the secondViewController and print out the boolean value
[self.navigationController popViewControllerAnimated:YES];
NSLog(@"The value of self.someBooleanValue is %s", self.someBooleanValue ? "YES" : "NO");
}
@end
SecondViewController.h
#import "FirstViewController.h"
@interface SecondViewController : UIViewController
// Create a 'weak' property to hold a reference to the firstViewController
@property (nonatomic, weak) FirstViewController *firstViewController;
@end
第二视图控制器.m
@implementation SecondViewController
/* When required (in this case, when a button is pressed),
set the property in the first view controller and ask the
firstViewController to dismiss the secondViewController */
- (IBAction)buttonPressed:(id)sender {
self.firstViewController.someBooleanValue = YES;
[self.firstViewController dismissSecondViewController];
}
@end
当然,处理这种viewController 间通信的最正确方法是使用协议/委托/数据源,这样SecondViewController 就不需要知道其父/所有者对象的细节。但是,有时构建这样的解决方案只是为了证明这个概念会更快/更简单。然后,如果一切顺利并且代码值得保留,请重构以使用协议。
在视图控制器不 - 也不应该 - 相互了解的情况下,可能需要使用 NSNotificationCenter。不要使用全局变量或 NSUserDefaults 在视图控制器之间进行通信。