这不是这样做的。你应该使用委托。
我假设我们有两个视图控制器,ViewController1和ViewController2,这个检查是在第一个视图控制器中,当它的状态发生变化时,您需要在ViewController2中执行一些操作。为了以正确的方式实现这一点,您应该执行以下操作:
向项目添加新文件(Objective-C协议)菜单文件→ 新现在将其命名为ViewController1Delegate或任何您想要的名称,并在@interface和@end指令之间编写这些命令:
@optional
- (void)checkStateDidChange:(BOOL)checked;
现在转到ViewController2.h并添加:
#import "ViewController1Delegate.h"
然后将其定义更改为:
@interface ViewController2: UIViewController<ViewController1Delegate>
现在转到ViewController2.m,在实现中添加:
- (void)checkStateDidChange:(BOOL)checked {
if (checked) {
// Do whatever you want here
NSLog(@"Checked");
}
else {
// Also do whatever you want here
NSLog(@"Not checked");
}
}
现在转到ViewController1.h并添加以下属性:
@property (weak, nonatomic) id<ViewController1Delegate> delegate;
现在,如果您在某个事件后在ViewController2内创建ViewController1,那么您应该使用NIB文件这样做:
ViewController1* controller = [[NSBundle mainBundle] loadNibNamed:@"ViewController1" owner:self options:nil][0];
controller.delegate = self;
[self presentViewController:controller animated:YES completion:nil];
现在你都准备好了。每当您检测到ViewController1中的检查事件发生更改时,您只需执行以下操作:
[delegate checkStateDidChange:checked]; // You pass here YES or NO based on the check state of your control