Cocoa开发中, 如何用全局变量

比如在tabbar的开发中,可以某个页面的数据需要在back到此页面后依然有效。

可以用 appDelegate 这个对象来创建你的全局数据

这个内建的对象,在 APP 启动时产生,在 APP 退出时销毁

下面是实例
假设我们给这个变量定义的名字为 GlobalValue

  1. 在 IphoneViewAppDelegate.h 中加入下面的代码(加在 interface 外)

    // 记录当次运行实例中 WebView 当前动作
    @property (nonatomic, retain) NSString *GlobalValue;

  2. 在 IphoneViewAppDelegate.m 文件的前面加入下面的代码

    // 记录当次运行实例中 WebView 当前动作
    @synthesize GlobalValue;

  3. 在 IphoneViewController.m 文件的 - (void)viewDidLoad 方法中加入下面的代码

    // 引入全局变量
    IphoneViewAppDelegate appDelegate = (IphoneViewAppDelegate)[[UIApplication sharedApplication] delegate];
    // 对变量写入
    appDelegate.GlobalValue = @"loading";

在你的文件 *.m 任意一个地方,都可以通过
IphoneViewAppDelegate *appDelegate = (IphoneViewAppDelegate)[[UIApplication sharedApplication] delegate];//这种写法会报警告,那么应当修改为直接调用

(IphoneViewAppDelegate *)[[UIApplication sharedApplication] delegate]。。。。
来获得这个全局的对象
然后可以对 appDelegate.GlobalValue 进行读写
在切换界面的过程中,也能读写这个变量,这个值会在退出 APP 时自动销毁

例子:

#import <UIKit/UIKit.h>

@class KidsViewController;

@interface KidsAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) KidsViewController *viewController;
@property (strong, nonatomic) IBOutlet UINavigationController *navController;
@property (strong, nonatomic) NSMutableArray *classList;
@property (strong, nonatomic) NSMutableArray *childList;
@property (nonatomic) int currentType;
@property (nonatomic, strong) NSString *currentSelectName;

@end

@implementation KidsAppDelegate
@synthesize classList = _classList;
@synthesize childList = _childList;
@synthesize currentType = _currentType;
@synthesize currentSelectName = _currentSelectName;

- (void)dealloc
{
    [_window release];
    [_currentSelectName release];
    [_viewController release];
    [_classList release];
    [_childList release];
    [super dealloc];
}

赋值和调用

- (void)getChildList:(NSMutableArray *)array
{
    if (array) {
        
        self.childArray = array;
        ((KidsAppDelegate*)[[UIApplication sharedApplication]delegate]).childList = self.childArray;
        
    }
    
}

 self.currentType = ((KidsAppDelegate*)[[UIApplication sharedApplication]delegate]).currentType;

有几种方法

some developers recommend use singleton patter (ref link http://blog.csdn.net/kmyhy/article/details/7026511)

方法1:使用静态变量 (不推荐)

方法2: 使用singleton pattern (ref link: http://nice.iteye.com/blog/855839

方法3:把全局变量设置到AppDelegate中

例: 定义和使用一个全局变量"isLogin"

AppDelegate.h

@interface AppDelegate :UIResponder <UIApplicationDelegate>

@property (strong,nonatomic)UIWindow *window;

@propertyBOOL isLogin;

@end


AppDelegate.m

@implementation AppDelegate

@synthesize window =_window;

@synthesize isLogin;

@end


那么在其他的class里,则可以通过下列代码调用全局变量

AppDelegate *delegate=(AppDelegate*)[[UIApplicationsharedApplication]delegate];

delegate.isLogin=YES;

原文地址:https://www.cnblogs.com/lisa090818/p/3433719.html