如何从应用程序委托访问视图控制器实例变量

How do I access a view controller instance variable from app delegate

我有一个 NSMutablearray,我想在应用程序进入后台时将其保存到文件中。我已经在 Viewcontroller.h 中将我的 NSMutablearray 声明为实例变量:

#import <UIKit/UIKit.h>

NSString *docPath();

@interface ViewController : UIViewController<UITableViewDataSource>

{
    UITableView *taskTable;
    UITextField *taskField;
    UIButton *insertButton;

    NSMutableArray *tasks;

}

- (void)addTask:(id)sender;


@end

现在我需要像这样在我的 AppDelegate 中访问这个变量:

- (void)applicationDidEnterBackground:(UIApplication *)application {

    [tasks writetofile:docPath() atomically:YES];

}

我对此很陌生并且是自学的。我认为 AppDelegate 中的某种#import "Viewcontroller.h" 会有所帮助,但不确定如何进行。任何帮助表示赞赏。

您可以注册 viewcontroller 后台通知。这里不需要Appdelegate。

- (void)viewDidLoad{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [tasks writetofile:docPath() atomically:YES];
}

编辑:

或者您可以迭代 navigation stack 以在 AppDelegate.

中获取您的 viewcontroller 实例
UINavigationController *navigationController = [self.window rootViewController];

for (UIViewController *viewController in navigationController.viewControllers) {
    if (viewController isKindOfClass:[YOUR_CONTROLLER class]) {

        YOUR_CONTROLLER *yourController =  (YOUR_CONTROLLER *)viewController;

        //Do your code using yourController instance
    }
}

注意:以上代码是基于假设你的rootviewcontroller是UINavigationController