Search code examples
iosobjective-cxcodeipaduiswitch

Writing the state of a UISwitch to file


I'm trying to write the state of a UISwitch to file, so every time the app starts up it remembers whether it was on or off previously.

-(IBAction) switchValueChanged {
   if (Hard1ON.on) {
   isH1 = (@"YES");
   //save above yes to file

After a bit of searching, I found this is the piece of code used to save to file:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile encoding:(NSStringEncoding)enc error:(NSError **)error

However it is evoking a 'Use of undeclared identifier 'writeToFile' error. Can anyone tell me what's wrong?


Solution

  • To save to a file as a string (likely not the best solution):

    - (IBAction)switchValueChanged:(id)sender
    {
        NSString *stateAsString;
        if ([sender isOn]) {
            stateAsString = @"YES";
        } else {
            stateAsString = @"NO";
        }
        [stateAsString 
            writeToFile:@"/path/to/file"
            atomically:NO 
            encoding:NSUTF8StringEncoding 
            error:NULL
        ];
    }
    

    It would probably be a better idea to write the state to NSUserDefaults:

    #define kSwitchStateKey @"SwitchState"
    
    - (IBAction)switchValueChanged:(id)sender
    {
        [[NSUserDefaults standardUserDefaults]
            setObject:@([sender isOn)
            forKey:kSwitchStateKey
        ];
    }