您的位置:首页 > 移动开发 > IOS开发

iOS项目中全局变量的定义与使用

2017-03-15 17:07 375 查看
 在一个项目中,我们可能需要定义几个全局变量,在我们程序的任何位置都可以进行访问,提高我们的开发效率。在iOS中我们如何来实现呢?我们主要使用的是AppDelegate类来实现。如下:

(1)AppDelegate.h:

[objc] view
plain copy

 print?

#import <UIKit/UIKit.h>  

  

@interface AppDelegate : UIResponder <UIApplicationDelegate>  

  

@property (strong, nonatomic) UIWindow *window;  

  

@property (strong,nonatomic) NSString *myName;//声明一个全局变量;  

  

  

@end  

(2)ViewController.m

这个是第一个页面。

[objc] view
plain copy

 print?

#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

这个是第二个页面。

[objc] view
plain copy

 print?

#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的对象,这个对象就是唯一的,所以就可以实现全局变量

原文地址:http://blog.csdn.net/chenyufeng1991/article/details/49282325
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: