在一个项目中,我们可能需要定义几个全局变量,在我们程序的任何位置都可以进行访问,提高我们的开发效率。在iOS中我们如何来实现呢?我们主要使用的是AppDelegate类来实现。如下:
(1)AppDelegate.h:
- #import <UIKit/UIKit.h>
-
- @interface AppDelegate : UIResponder <UIApplicationDelegate>
-
- @property (strong, nonatomic) UIWindow *window;
-
- @property (strong,nonatomic) NSString *myName;
-
-
- @end
(2)ViewController.m
这个是第一个页面。
- #import "ViewController.h"
- #import "AppDelegate.h" //需要引入这个头文件;
-
-
- @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 = @"第一个页面";
-
- }
-
-
- @end
(3)SecondViewController.m
这个是第二个页面。
- #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 = @"第二个页面";
-
- }
-
- @end
最后在两个页面之间跳转,输出结果如下:
。
这表示我们对同一个变量进行了操作。为什么在AppDelegate中可以声明全局变量呢?因为使用了单例,AppDelegate就是一个单例的类,实现了UIApplicationDelegate这个委托。只要我们在程序的任何地方声明了AppDelegate的对象,这个对象就是唯一的,所以就可以实现全局变量
iOS全局变量的声明和使用
原文:http://www.cnblogs.com/sunfuyou/p/7119827.html