好比在tabbar的开发中,能够某个页面的数据须要在back到此页面后依然有效。app
能够用 appDelegate 这个对象来建立你的全局数据post
这个内建的对象,在 APP 启动时产生,在 APP 退出时销毁atom
下面是实例
假设咱们给这个变量定义的名字为 GlobalValuespa
在 IphoneViewAppDelegate.h 中加入下面的代码(加在 interface 外).net
// 记录当次运行实例中 WebView 当前动做
@property (nonatomic, retain) NSString *GlobalValue;code
在 IphoneViewAppDelegate.m 文件的前面加入下面的代码orm
// 记录当次运行实例中 WebView 当前动做
@synthesize GlobalValue;对象
在 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
AppDelegate *delegate=(AppDelegate*)[[UIApplicationsharedApplication]delegate];
delegate.isLogin=YES;