ios AppDelegate设置全局变量

本文介绍了如何在iOS应用中利用AppDelegate的单例模式来设置和传递全局变量。通过在AppDelegate中定义属性,并在不同类中通过[[UIApplication sharedApplication] delegate]获取AppDelegate实例,实现值的共享。文中给出了在AViewController中设置值,然后在BViewController中读取并打印该值的例子,展示了全局变量的使用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    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






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值