John
John

Reputation: 353

Losing data variable on changing view in iOS

I have a variable in my viewcontroller.h declared as

@property (nonatomic) uint size;

On the viewcontrooler.m, I set a value to this variable when a button is pressed.

The problem is, when I change a view and return back, the value of my variable is lost.

What can i do do solve that? I don't need to declare it as a global variable, because I just use it in the ViewController.m.

Upvotes: 2

Views: 326

Answers (1)

Ladislav
Ladislav

Reputation: 7283

What I would do is on viewWillDissapear I would save the value with

[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%i", size] forKey:@"mySize"];

and I would just retrieve this value on viewWillAppear with

size = [[[NSUserDefaults standardUserDefaults] objectForKey:@"mySize"] intValue];

Then if you wants to delete the value from app just use:

[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"mySize"];

One thing I would also try is declaring the property without non atomic (maybe you will retain the value between screens because of that!):

@property uint size;

Upvotes: 3

Related Questions