0

我有一个 int ,每次视图重新打开/离开时都会自行重置。我已经尝试了所有我能想到的声明 int 的方法,从公共到实例变量再到全局变量,但它似乎仍然重置!

@interface MainGameDisplay : UIViewController
extern int theDay;

@implementation MainGameDisplay

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%i", theDay);
}

- (IBAction)returnToHome:(id)sender {
        ViewController *new = [[ViewController alloc] initWithNibName:nil bundle:nil];
        [self presentViewController: new animated:YES completion:NULL];
        NSLog(@"%i", theDay);
}

- (IBAction)theDayAdder:(id)sender {
    theDay++;
}

好的,所以 theDay 是一个全局整数变量。在 View load NSLog 返回输出 0。然后我可以根据需要多次单击 theDayAdder,当我单击 returnToHome 时,它​​会告诉我 theDay 是什么。然而,当我回到 MainGameDisplay 页面时,theDay 将被重置为零,即使它是一个全局变量?

Output:
0
N (number of times you clicked 'theDayAdder' button)
0
4

3 回答 3

1

问题是您每次返回 MainGameDisplay 时都会分配一个新实例,因此您的全局变量当然会重置为 0。您需要在 ViewController 中创建一个属性(类型为强),使用它来每次都回到同一个实例。

- (IBAction)returnToGameDisplay:(id)sender {
     if (! self.mgd) {
        self.mgd = [[MainGameDisplay alloc] initWithNibName:nil bundle:nil];
     }
     [self presentViewController: self.mgd animated:YES completion:NULL];
     NSLog(@"%i", theDay);
}

在此示例中,mgd 是在 .h 文件中创建的属性名称。

于 2012-11-11T00:50:10.373 回答
0

extern变量应该是恒定的。如果您希望您的MainGameDisplay类是长期存在的,或者如果theDay只应该与该类相关联,为什么不将 theDay 声明为属性,或者,如果您只需要在 MainGameDisplay 内部将其设置为 ivar .

如果您希望该值独立于声明它的类实例继续存在,另一种选择是声明它static。静态 var 将保留其值,即使在声明它的类的不同实例的生命周期中也是如此。

于 2012-11-11T01:18:36.397 回答
0

您应该知道 viewDidLoad() 是在加载视图时调用的——而不是在视图“打开”时调用。您可能会在保留值中打开一个视图,然后一次又一次地重新打开,并且只调用一次 vieDidLoad()。然而,每当视图变得可见时,viewWillAppear() 就是被调用的委托。因此,尝试在 viewWillAppear() 中输出您的值——而不是 viewDidLoad() 并适当地调用视图(即,让它保持不变,而不是在每次需要时创建)。这将防止视图在调用之间被破坏。您的视图代码应如下所示:

@interface MainGameDisplay : UIViewController
extern int theDay;

@implementation MainGameDisplay

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void) viewWillAppear:(BOOL) animated {
    [super viewWillAppear:animated];
    NSLog(@"%i", theDay);
}

- (IBAction)returnToHome:(id)sender {
        ViewController *new = [[ViewController alloc] initWithNibName:nil bundle:nil];
        [self presentViewController: new animated:YES completion:NULL];
        NSLog(@"%i", theDay);
}

- (IBAction)theDayAdder:(id)sender {
    theDay++;
}

视图的父级(我假设 appDelegate)应该执行以下操作

@property (nonatomic, strong) MainGameDisplay *mainGameDisplay = [[MainGameDisplay alloc] initWithNib:@"MainGameDisplay" …]

ViewDidLoad() 被调用一次——在视图被创建和加载之后。但是,由 IBAction 等触发的 viewWillAppear() 和其他函数被适当地调用。

于 2012-11-11T01:01:03.887 回答