您的位置:首页 > 移动开发

ios AppDelegate设置全局变量

2014-08-27 14:04 375 查看
IOS每个程序都会有一个AppDelegate类,这个类是一个单例模式。单例模式的意思是,该类在整个程序中只被实例化一次。因此,利用单例模式的appDelegate类可以在整个程序中传递数值。

在使用appDelegate类时注意一点,不要用init方法去实例化它,这样得到每个的对象都是新的对象,也失去了传值的意义,而是要使用:

AppDelegate *app = [[UIApplicationsharedApplication]delegate];

这样的方式,然后再对AppDelegate的属性进行赋值,例如在A类中将appdelegate的某个属性赋值,那么在B类中得到的appdelegate的该属性值还是A类中赋的。

具体看例子:

在AppDelegate中定义一个属性str:

<span style="color:#333333;">#import <UIKit/UIKit.h>
#import "AViewController.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

{
AViewController *aVC;
NSString *str;
}

@property (nonatomic, strong) NSString *str;//</span><span style="color:#ff0000;">定义的目标属性</span><span style="color:#333333;">

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end</span>
在A类中赋值:

#import "AViewController.h"
#import "BViewController.h"
#import "AppDelegate.h"

@interface AViewController ()

@end

@implementation AViewController

- (void)viewDidLoad
{
[super viewDidLoad];

AppDelegate *app = [[UIApplication sharedApplication] delegate];//单例初始化方式
app.str = @"aaa";
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(10, 200, 300, 40);
[btn setTitle:@"next" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
<pre name="code" class="objc">- (void)next
{
BViewController *bVC = [[BViewController alloc] init];
[self.navigationController pushViewController:bVC animated:YES];
}


在B类中取值:

#import "BViewController.h"

@interface BViewController ()

@end

@implementation BViewController

@synthesize app;

- (void)viewDidLoad
{
[super viewDidLoad];
app = [[UIApplication sharedApplication] delegate];
NSLog(@"B类接受的结果为:%@", app.str);
}


得到的结果为:

2014-08-27 14:22:16.959 TestAppDelegate[4360:60b] B类接受的结果为:aaa
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: