NSUserDefaults Question?

Discussion in 'iOS Programming' started by jessejohnson147, Feb 4, 2010.

  1. jessejohnson147 macrumors newbie

    Joined:
    Jun 5, 2009
    #1
    Right now I have a button that turns a view's alpha on and off with a if then statement. I have been trying to get the view to stay on or off with the NSUserDefaults with no luck. I think I have seen every tutorial out there for NSUserDefaults can anyone help?
     
  2. csnplt macrumors 6502

    csnplt

    Joined:
    Aug 29, 2008
    Location:
    Chicago Area
    #2
    What's your code look like? Here's what I'd do:

    In IB, connect your button to this action method:
    Code:
    -(IBAction)hideView
    {
    	BOOL isCurrentlyHidden = [[NSUserDefaults standardUserDefaults] boolForKey:@"viewHidden"];
    	
    	[[NSUserDefaults standardUserDefaults] setBool:(!isCurrentlyHidden) forKey:@"viewHidden"];
    	
    	if([[NSUserDefaults standardUserDefaults] boolForKey:@"viewHidden"] == YES)
    		myView.hidden = YES;
    	else myView.hidden = NO;
    	
    	
    }
    
    Now, in ViewDidLoad, set the view up, assuming it was set up in IB:
    Code:
    -(void)viewDidLoad 
    {
          if([[NSUserDefaults standardUserDefaults] boolForKey:@"viewHidden"] == YES)
    		myView.hidden = YES;
    	else myView.hidden = NO;
    }
    
    If the app has not been run before, there will be no bool set for the key "viewHidden." NSUserDefaults will return NO for the value, so by default, the view will be shown.

    Tell me how this works.
     
  3. Darkroom Guest

    Darkroom

    Joined:
    Dec 15, 2006
    Location:
    Montréal, Canada
    #3
    registering notifications with your objects can make dealing with what's on and what's off a lot more simple when dealing with reading and writing userdefaults.
     

Share This Page