iPhone开发之全局变量的使用

全局变量历来就是很好的东西,能够在开发中带来很多方便,下面来介绍一下iPhone中软件开发时全局变量的使用方法:

1.使用extern关键字

在AppDelegate.m或AppDelegate.h中写入你需要的全局变量名,例如:int  name;NSString *url;注意定义全局变量时候不能初始化,否则报错。

#import <UIKit/UIKit.h>

@class ViewController;

int name ;
NSString *url;

@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) ViewController *viewController; @property (nonatomic) int y; @end

在需要调用的.m文件中声明 extern int name; 然后就可以使用了。

extern int name;
extern NSString *url;

@interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"在另一个页面调用第一次使用之后:%d",name); name = 2; NSLog(@"第二复制之后%d",name);

  url = [URL copy]; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; NSLog(@"appDelegate.y = %d",appDelegate.y); appDelegate.y = 5; NSLog(@"appDelegate.y = %d",appDelegate.y); NSLog(@"单例第一次使用:%@",[Singleton sharedSingleton].user); [Singleton sharedSingleton].user = @"单例第er次使用"; NSLog(@"单例第二次使用:%@",[Singleton sharedSingleton].user); // Do any additional setup after loading the view, typically from a nib. }

第二种方法:单例

原文地址:https://www.cnblogs.com/superchao8/p/2862362.html