在AppDelegate中更改var的值

ton*_*ran 3 iphone uiapplicationdelegate ios5

在我的AppDelegate中,我有

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

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

@end
Run Code Online (Sandbox Code Playgroud)

在B班,我做

AppDelegate *appDelegate        =   [[UIApplication  sharedApplication] delegate];
appDelegate.x   =   5;
Run Code Online (Sandbox Code Playgroud)

然后在C级,我做

 AppDelegate *appDelegate        =   [[UIApplication  sharedApplication] delegate];
 appDelegate.x   =   4;
Run Code Online (Sandbox Code Playgroud)

最后,在DI类打印出x和x = 5的结果 .应该是4.这令我感到困惑.请就此问题向我提出建议.谢谢

Mar*_*oGT 6

在您的App委托方法中,您的属性x设置为strong(也就是保留),您必须设置为assign,因为它不是对象,所以无法保留int var:

@property (assign, nonatomic, readwrite) int x; //then @synthesize in the implementation
Run Code Online (Sandbox Code Playgroud)

其次,你必须导入appDelegate的标题(在你的B,C,D类中)

#import "yourAppDelegate.h" 
Run Code Online (Sandbox Code Playgroud)

设置你的appDelegate实例:

yourAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate]; // or [NSApplication sharedApplication] if your app it is for OS X
Run Code Online (Sandbox Code Playgroud)

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

appDelegate.x = 5 (or whatever)
Run Code Online (Sandbox Code Playgroud)

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