How to access view controller variables from the app delegate... and vice versa?
cocoa-touch, ios, objective-c
Solution
Part 1: In the ViewController.h:
-(int)mouse; //add this before the @end
In the ViewController.m, add this method:
-(int)mouse
{
return mouse;
}
To access mouse from AppDelegate, use self.viewController.mouse For example;
NSLog(@"ViewController mouse: %i", self.viewController.mouse);
Part2:
In the AppDelegate.h:
-(int)dog; //add this before the @end
In the AppDelegate.m, add this method:
-(int)dog
{
return dog;
}
In the ViewController.m:
#import "AppDelegate.h"
To access dog from ViewController, use this:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"dog from AppDelegate: %i", [appDelegate dog]); //etc.
Problem
I would like the view controller to be able to access `dog` in the app delegate. I would like the app delegate to be able to access `mouse` in the view controller. ``` #import <UIKit/UIKit.h> @interface ViewController : UIViewController { int mouse; // <---------------- } @end ``` ``` - (void)viewDidLoad { [super viewDidLoad]; mouse = 12; // <------------------- NSLog(@"viewDidLoad %d", dog); // <--------------- } ``` ``` #import <UIKit/UIKit.h> @class ViewController; @interface AppDelegate : UIResponder <UIApplicationDelegate> { int dog; // <--------------- } @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) ViewController *viewController; @end ``` ``` - (void)applicationWillResignActive:(UIApplication *)application { NSLog(@"applicationWillResignActive %d", mouse); // <-------------- } ``` ``` - (void)applicationDidBecomeActive:(UIApplication *)application { dog = 77; // <--------------------- NSLog(@"applicationDidBecomeActive"); } ```