IOS全局变量

Wesley13
• 阅读 985

IOS中的全局变量和JAVA中的全局变量定义和使用方法不一样,在Java中,只需要将变量定义为static就行了。而在IOS中这种方法不适合。

IOS中定义全局变量有三种方法:

1.使用extern关键字

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

#import <UIKit/UIKit.h>

@class ViewController;

int name ;
@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;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"在另一个页面调用第一次使用之后:%d",name);
    name = 2;
    NSLog(@"第二复制之后%d",name);
    
    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.
}

2.在AppDelegate中生命并出事后全局变量,然后在需要使用该变量的地方调用如下代码

xxxAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; appDelegate.Your Variable

3.将全局变量定义未一个单例类的变量。

上说三种方式的参考代码:

//
//  AppDelegate.h
//  _1217_GlobalDemo
//
//  Created by yier on 12-12-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@class ViewController;

int name ;
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;
@property (nonatomic) int y;

@end

//
//  AppDelegate.m
//  _1217_GlobalDemo
//
//  Created by yier on 12-12-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"

#import "ViewController.h"
#import "Singleton.h"

extern int name;

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize y;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    NSLog(@"未使用全局变量之前:%d",name);
    name = 1;
    NSLog(@"第一次使用之后:%d",name);
       self.y = 2;
    [Singleton sharedSingleton].user = @"单例第一次使用";
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
 
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

//
//  ViewController.m
//  _1217_GlobalDemo
//
//  Created by yier on 12-12-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import "Singleton.h"


extern int name;

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"在另一个页面调用第一次使用之后:%d",name);
    name = 2;
    NSLog(@"第二复制之后%d",name);
    
    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.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

//  Singleton.h
//  _1217_GlobalDemo
//
//  Created by yier on 12-12-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Singleton : NSObject

@property (nonatomic, retain) NSString *user;

+ (Singleton *)sharedSingleton;

@end

//
//  Singleton.m
//  _1217_GlobalDemo
//
//  Created by yier on 12-12-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Singleton.h"

@implementation Singleton
@synthesize user;

+ (Singleton *)sharedSingleton{
    static Singleton *sharedSingleton = nil;
    @synchronized(self){
        if (!sharedSingleton) {
            sharedSingleton = [[Singleton alloc] init];
            return sharedSingleton;
        }
    }
    return sharedSingleton;
}
@end
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
PhoneGap设置Icon
参考:http://cordova.apache.org/docs/en/latest/config\_ref/images.html通过config.xml中的<icon标签来设置Icon<iconsrc"res/ios/icon.png"platform"ios"width"57"height"57"densi
Stella981 Stella981
3年前
JS 苹果手机日期显示NaN问题
问题描述newDate("2019122910:30:00")在IOS下显示为NaN原因分析带的日期IOS下存在兼容问题解决方法字符串替换letdateStr"2019122910:30:00";datedateStr.repl
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这