我希望视图控制器能够访问应用程序委托中的狗.
我希望应用程序委托能够在视图控制器中访问鼠标.
#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"); }
解决方法
第1部分:
在ViewController.h中:
在ViewController.h中:
-(int)mouse; //add this before the @end
-(int)mouse { return mouse; }
要从AppDelegate访问鼠标,请使用self.viewController.mouse
例如;
NSLog(@"ViewController mouse: %i",self.viewController.mouse);
第2部分:
在AppDelegate.h中:
-(int)dog; //add this before the @end
-(int)dog { return dog; }
在ViewController.m中:
#import "AppDelegate.h"
要从ViewController访问dog,请使用以下命令:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSLog(@"dog from AppDelegate: %i",[appDelegate dog]); //etc.