0

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?

Louis Holley
  • 135
  • 1
  • 3
  • 10
  • 1
    Can you post the code where you're calling `writeToFile`? – lxt Feb 24 '13 at 11:14
  • You might want to consider `NSUserDefaults` for this: http://stackoverflow.com/a/4231746/653513 Anyway, the code you posted has nothing to do with the error: see lxt's comment. – Rok Jarc Feb 24 '13 at 11:18

1 Answers1

1

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
    ];
}            
puzzle
  • 6,071
  • 1
  • 25
  • 30