In a project, we may need to define several global variables that can be accessed anywhere in our program to improve our development efficiency. How do we implement it in iOS? We mainly use the Appdelegate class to implement. As follows:
(1) AppDelegate.h:
- #import <UIKit/UIKit.h>
- @interface Appdelegate:uiresponder <UIApplicationDelegate>
- @property (Strong, nonatomic) UIWindow *window;
- @property (Strong,nonatomic) nsstring *myname; declares a global variable;
- @end
(2) VIEWCONTROLLER.M
This is the first page.
- #import "ViewController.h"
- #import "AppDelegate.h"//need to introduce this header file;
- @interface Viewcontroller ()
- @end
- @implementation Viewcontroller
- -(void) Viewdidload {
- [Super Viewdidload];
- }
- -(void) Viewdidappear: (BOOL) animated{
- [Super Viewdidappear:true];
- appdelegate *app = [[uiapplication Sharedapplication] delegate];
- NSLog (@ "%@", App. myName);
- App. myName = @ "First page";
- }
- @end
(3) SECONDVIEWCONTROLLER.M
This is the second page.
- #import "SecondViewController.h"
- #import "AppDelegate.h"
- @interface Secondviewcontroller ()
- @end
- @implementation Secondviewcontroller
- -(void) Viewdidload {
- [Super Viewdidload];
- }
- -(void) Viewdidappear: (BOOL) animated{
- appdelegate *app = [[uiapplication Sharedapplication] delegate];
- NSLog (@ "%@", App. myName);
- App. myName = @ "second page";
- }
- @end
Finally jump between two pages, the output is as follows:
。
This means we are working on the same variable. Why is it possible to declare global variables in appdelegate? Because a singleton is used, Appdelegate is a singleton class that implements the Uiapplicationdelegate delegate. As long as we declare the Appdelegate object anywhere in the program, this object is unique, so we can implement the global variable
Declaration and use of iOS global variables