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");
}
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.
In your view controller header file add mouse as a property:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
NSInteger mouse; // <----------------
}
@property (nonatomic, assign) NSInteger mouse;
@end
Synthesize the property in your view controller implementation just below the @implementation line:
@synthesize mouse;
In your app delegate add dog as a property:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSInteger dog; // <---------------
}
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (nonatomic, assign) NSInteger dog;
@end
Also synthesize dog in your app delegate implementation.
Now in your app delegate, assuming you have a reference to your view controller, you can access mouse like this:
viewController.mouse = 13;
You can do the same thing with your app delegate class, which can be accessed from any view controller using (assuming the name of your app delegate class is AppDelegate):
((AppDelegate *)([UIApplication sharedApplication].delegate)).dog = 13;
I would recommend that you use also use NSInteger instead of int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With