Search code examples
iosvariablesfixed

Make a variable with a fixed value


I've a view controller with one variable x, in ViewController.h:

@property(nonatomic) int x;

Is it possible to set the recent value of x fixed? For example a method sets x to the value 5 and when this view controller is reloaded the value of x should be 5 and not 0 again as it is now.

e.g. in a ViewController:

- (IBAction)btnPressed:(id)sender {
_x++;
}

x should be increase after each tapping of the button >>> 0,1,2,3,4...(even after a restart of the app)

Thanks to all your answers in advance.


Solution

  • You can use simple and clear methods to store your value.

    Your interface:

    @interface FirstViewController : UIViewController
    
    @property (nonatomic) int x;
    @property (strong, nonatomic) IBOutlet UILabel *label;
    
    - (IBAction)buttonPressed:(id)sender;
    - (void)updateLabel;
    
    @end
    

    Your setter:

    - (void)setX:(int)x
    {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setInteger:x forKey:@"MyValue"];
        [userDefaults synchronize];
    }
    

    Your getter:

    - (int)x
    {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        return [userDefaults integerForKey:@"MyValue"];
    }
    

    Your action:

    - (IBAction)buttonPressed:(id)sender 
    {
        [self updateLabel];
        self.x++;
    }
    

    Your viewDidAppear: method:

    - (void)viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        [self updateLabel];
    }
    

    Your method to update label:

    - (void)updateLabel
    {
        [self.label setText:[NSString stringWithFormat:@"%d", self.x]];
    }
    

    Notes:

    1. @"MyValue" has to be unique string, because UserDefaults is only instance for whole application.
    2. integerForKey is method to store int values only.

    Updated: I'm sorry, integerForKey is right method here, thanks to @JoshHinman.