【问题标题】:change value of var in AppDelegate更改 AppDelegate 中 var 的值
【发布时间】:2012-01-05 05:16:20
【问题描述】:

在我的 AppDelegate 中,我有

#import <UIKit/UIKit.h>
#import "CustomerProfile.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property   (strong, nonatomic) UIWindow *window;
@property   (strong, nonatomic) int x;

@end

在B班,我愿意

AppDelegate *appDelegate        =   [[UIApplication  sharedApplication] delegate];
appDelegate.x   =   5;

然后在C班,我做

 AppDelegate *appDelegate        =   [[UIApplication  sharedApplication] delegate];
 appDelegate.x   =   4;

最终,在 D 类中,我打印出 x 和 x = 5 的结果。 x 应该是 4。 这让我很困惑。请就这个问题给我建议。 谢谢

【问题讨论】:

  • 为澄清起见,您按以下顺序初始化类:B 类 - C 类 - D 类?
  • 包含 D 类中的代码,并将日志语句放在 B 和 C 中的赋值以及 D 中的读取之前,以便您可以验证这些语句的运行顺序。

标签: iphone ios5 uiapplicationdelegate


【解决方案1】:

在您的 App 委托方法中,您的属性 x 设置为强(也称为保留),您必须设置为分配,不能保留 int var,因为它不是对象:

@property (assign, nonatomic, readwrite) int x; //then @synthesize in the implementation

其次,您必须导入 appDelegate 的标头(在您的 B、C、D 类中)

#import "yourAppDelegate.h" 

设置您的 appDelegate 实例:

yourAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; // or [NSApplication sharedApplication] if your app it is for OS X

然后将您的 x var 设置为所需的值

appDelegate.x = 5 (or whatever)

我在我的一个项目和作品中对此进行了测试。

【讨论】:

  • 在 C 中将 x 的值更改为 4 并且您在 D 中获得了新的 4 的 C。这是您的意思吗?但是我可以设置 x 的值。然后我改变了 x 的值,我仍然得到最旧的值(在这种情况下是 5)
  • 我修复了答案中的代码,我忘了写 x 值:appDelegate.x = 5。在我的测试中,我在几个类中设置了 x 值,然后记录 x NSLog(@"%d",appDelegate.x) 的值,我设置了新值,而不是像你这样的旧值。
  • 是的,你很有礼貌,我做了改变,我得到了我想要的......谢谢
猜你喜欢
  • 2016-04-12
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多