0
votes

I am making an application in which i have added the settings(nsuserdefaults)

The problem is in my mainviewcontroller i declare user defaults and get its values. However since viewdidload is not called after user goes to settings and comes back to the app. My settings does not update.

I tried declaring user defaults in app delegate applicationwillenterforeground but how will i pass the message to mainviewcontroller.

variables defined in app delegate are not recognised in mainviewcontroller.

Update : I have declared

- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSUserDefaults *prefs = [NSUserDefaults  standardUserDefaults];
}

i have toggle switch in settings which has identifier enabled_preference so i wrote

   else
{
    [PlaySound prepareToPlay];      
    [prefs setBool:YES forKey:@"enabled_preference"];
    BOOL loop = [prefs boolForKey:@"enabled_preference"];
    NSLog(@" %d",loop);
    do {
          [PlaySound play];
    } while (loop ==YES);

it is logging 0 in console however i have set default to yes in plist

3

3 Answers

2
votes

you can use any where in app if you set object to NSUserDefaults.. no need to create object in appDelagate...

[[NSUserDefaults standardUserDefaults] setObject:@"Ramu" forKey:@"iCustomerId"];
[[NSUserDefaults standardUserDefaults] synchronize];

you can get that value in entire app using below line

[[NSUserDefaults standardUserDefaults] valueForKey:@"iCustomerId"]
1
votes

When you pop back your ViewDidLoad wont be called. You need to write that code in

ViewWillAppear

and that is called every time you to that view controller.

1
votes

Any object can register itself for the application did become active notification. Just do that in your MainViewController:

@implementation MainViewController

- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self]; // your app may crash randomly if you don't do this

  [super dealloc];
}

- (void)applicationDidBecomeActive:(NSNotification *)notification
{
  // check user defaults for changes
}

@end

Depending on how your app is structured this particular applicationDidBecomeActive: method may or may not be called the first time your app is launched, you'll have to check, but it will always be called after that.