Saving the state of a switch

Discussion in 'iOS Programming' started by pesto10, Nov 15, 2010.

  1. pesto10 macrumors newbie

    Joined:
    Nov 15, 2010
    #1
    Hey Everyone,

    Nearly on the verge of completing my first app

    Its only a countdown one but ive learnt loads doing it so far, not coming froma programming background hasnt really helped but anyway.

    The last thing i need to is save the state of a switch i have on the settings page, currently it does its job by stopping the bacground music.

    Problem is if i exit the settings page then go back to it the switch is set back to 'on'

    Ive been reading 'sams teach yourself in 24hrs book' and i think ive sort of got the idea but its not quite there.

    Code:
    #import "SettingsViewController.h"
    #import <AudioToolbox/AudioServices.h>
    
    
    @implementation SettingsViewController
    
    @synthesize theAudio;
    @synthesize muteSwitch;
    
    - (IBAction) switchValueChanged{  
    	
        if ([muteSwitch isOn])  
            [muteSwitch setOn:NO animated:YES];  
        else   
            [muteSwitch setOn:YES animated:YES];  
    }  
    
    
    - (IBAction) toggleButtonPressed{
    	if(muteSwitch.on){
    		[theAudio play];
    	}
    	else{
    		[theAudio stop];
    		
    	}
    }
    
    - (IBAction) volume{
    	theAudio.volume = slider.value;
    
    }
    
    - (void) viewWillDisappear:(BOOL)animated{
    	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    	[userDefaults setBool:muteSwitch.on forKey:kOnOffToggle];
    	[userDefaults setBool:slider.value forKey:kSoundLevel];
    	
    	[super viewWillDisappear:animated];
    	
    }
    
    
    
    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
    	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    	[userDefaults setInteger:slider.value forKey:kSoundLevel];
    	muteSwitch.on = [userDefaults boolForKey:kOnOffToggle];
    	
    	
        [super viewDidLoad];
    }
    @end
    
    At the minute the switch and slider are working but the switch starts in the 'off' position instead of the 'on' position and the position of the slider doesnt stay the same.

    Could anyone point me in the right direction?

    If not no worries :p
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    I would restore the state in viewWillAppear rather than viewDidLoad
     
  3. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    Surely not as having 2 MR accounts is a short cut to having 0 MR accounts.
     

Share This Page