Search code examples
objective-cuiviewcontrollerappdelegateinstance-variables

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


I have a NSMutablearray that I want to save to file when the application enters background. I have declared my NSMutablearray in my Viewcontroller.h as an instance variable:

#import <UIKit/UIKit.h>

NSString *docPath();

@interface ViewController : UIViewController<UITableViewDataSource>

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

    NSMutableArray *tasks;

}

- (void)addTask:(id)sender;


@end

Now I need to access this variable in my AppDelegate like so:

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

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

}

I am fairly new to this and self taught. I thought some sort of #import "Viewcontroller.h" in the AppDelegate would help, but not sure how to proceed. Any help appreciated.


Solution

  • You can register your viewcontroller for background notification. There is no need for Appdelegate here.

    - (void)viewDidLoad{
        [super viewDidLoad];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    
    - (void)applicationDidEnterBackground:(UIApplication *)application {
        [tasks writetofile:docPath() atomically:YES];
    }
    

    EDIT:

    OR you can iterate the navigation stack to get your viewcontroller instance in AppDelegate.

    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
        }
    }
    

    NOTE: The above code is based on the assumption that your rootviewcontroller is UINavigationController