Cocoa開發中, 如何用全局變量

好比在tabbar的開發中,能夠某個頁面的數據須要在back到此頁面後依然有效。app

能夠用 appDelegate 這個對象來建立你的全局數據post

這個內建的對象,在 APP 啓動時產生,在 APP 退出時銷燬atom

下面是實例
假設咱們給這個變量定義的名字爲 GlobalValuespa

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

    // 記錄當次運行實例中 WebView 當前動做
    @property (nonatomic, retain) NSString *GlobalValue;code

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

    // 記錄當次運行實例中 WebView 當前動做
    @synthesize GlobalValue;對象

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

    // 引入全局變量
    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;

相關文章
相關標籤/搜索