iOS UIStepper & NSUserDefaults - How to manage them together and use a double

276 views Asked by At

I have the following code. However, the line

stepper.value = [NSNumber numberWithDouble:loadNumber];

errors with the error 'Sending NSNumber *__strong to a parameter of incompatible type 'double''. I think the stepper will only accept a double, but am unsure what I am doing wrong to set it.

What I need to achieve is the following:-

1) Have a default value set in NSUserDefaults for saveNumber, which will be used until a variation is made by the user.

2) on load or view appearing, use saveNumber to set the value of both stepper.value and myLabel.

3) ensure that when changed with the stepper, the value is updated in myLabel, and NSUserDefaults saveNumber is also updated.

Can anyone advise where I am going wrong, and help correct my code please?

Further,I just realised that in the final app, I will have this setting on a different viewController to the one that will use the NSUserDefaults savedNumber value. With this in mind, can you also let me know how to ensure that savedNumber is available not only to this viewController, but any other one I require the values on?

Many thanks.

- (void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSNumber *loadNumber = [defaults objectForKey:@"saveNumber"];
    self.myLabel.text = [NSString stringWithFormat:@"%@",loadNumber];
    UIStepper *stepper = [[UIStepper alloc] init];
    stepper.value = [NSNumber numberWithDouble:loadNumber];
}

- (IBAction)stepChanged:(id)sender {
    NSNumber *saveNumber = [NSNumber numberWithDouble:[(UIStepper *)sender value]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:saveNumber forKey:@"saveNumber"];
    [defaults synchronize];
    self.myLabel.text = [NSString stringWithFormat:@"%@",saveNumber];
}

I have one outstanding issue which is that I cannot get the defaults to deliver if no value has been set!

I have the following code in AppDelegate.m:-

    NSDictionary *defaults = @{ @"saveNumber": @8 };
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

When the App first launches (and every time after until the stepper has been used) the value being seen is 'null'.

Any ideas?

1

There are 1 answers

13
rmaddy On BEST ANSWER

This:

stepper.value = [NSNumber numberWithDouble:loadNumber];

needs to be:

stepper.value = [loadNumber doubleValue];

And you don't need to call synchronize after setting the value in NSUserDefaults.

A value stored in NSUserDefaults can be accessed from any class, not just the class that sets it.

Update:

To set a default value you want the following:

NSDictionary *defaults = @{ @"saveNumber": @6 };
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

This will set a default value of 6 for @"saveNumber".