1

I'm reading and writing variables to a text file in my app.

It works perfectly fine when testing it in the simulator, but somehow when testing it on the iPhone it can only read the file but not write/save anything

Here's my method for saving my variables ("\n" is used for line breaking):

NSString path = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"txt"];

- (void)saveSettings {
    [[NSString stringWithFormat:@"%d\n%d", firstInt, secInt] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

As I said: works in the simulator but doesn't work on any iDevice.

Does anyone got a idea why it's not working? Changing "atomically" to "NO" does nothing

YourMJK
  • 1,429
  • 1
  • 11
  • 22
  • If you rename your question as: **iOS7: Saving settings to file doesn't work on device**, it won't be a duplicate. From both the content of your question and your approved answer, it seems that the key element is `how to save preferences`, not `how to overwrite main bundle`. – SwiftArchitect Jul 15 '14 at 06:30
  • @Lancelot de la Mare I'm sorry, I changed it – YourMJK Jul 15 '14 at 14:34

2 Answers2

2

You can't write to the bundle. Among other reasons because the bundle is part of the signature in the app and that can't be changed. You can write to other directories, en particular the Documents directory

 NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];

 NSString *write_file = [NSString stringWithFormat:@"%@/settings.txt", 
                                                      documentsDirectory];

You will be able to write to write_file.

fsaint
  • 8,759
  • 3
  • 36
  • 48
  • 1
    Good answer, but why `write_file` as the variable name rather than `writeFile`? Also, you should probably be using `stringByAppendingPathComponent:`. – Ashley Mills Jul 14 '14 at 21:50
  • Answer to both of @Ashley Mills questions: because if you don't answer the easy ones fast you don't the the points! – fsaint Jul 14 '14 at 22:00
  • Thanks I didn't know that. But in my case I will go with the accepted answer because it seems like a better way – YourMJK Jul 14 '14 at 22:05
1

Short answer: You can't write into the main bundle.

Long answer: You should really use the preferences for this:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSString stringWithFormat:@"%d\n%d", firstInt, secInt]
    forKey:@"yourPref"];
BOOL saved = [prefs synchronize];

or even better, like that:

NSInteger firstInt = 0;
NSInteger secInt = 0;

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:firstInt forKey:@"firstInt"];
[prefs setInteger:secInt forKey:@"secInt"];
BOOL saved = [prefs synchronize];
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179