-2

Possible Duplicate: Problem in writing to a file in application bundle

I am trying to write a String to a file using the following code :

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

NSLog(@"Path : , %@", file);

NSError *error=NULL;

NSString *data=@"teleiwne";

[data writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&error];

The print out of Path is : /Users/kd/Library/Application Support/iPhone Simulator/6.0/Applications/763B8245-CB1A-4BDE-85CF-19AEFA411DB8/testKremala.app/settings.txt

I don't get any error but nothing is written to file

I tried the following code and it worked :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"];

NSString *data=@"Kostas";

[data writeToFile:appFile atomically:YES];

NSString *myData = [NSString stringWithContentsOfFile:appFile];

NSLog(@"Data : %@ ",myData);
Community
  • 1
  • 1
Kostas
  • 1,504
  • 1
  • 11
  • 13
  • possible duplicate of [Problem in writing to a file in application bundle](http://stackoverflow.com/questions/3564153/problem-in-writing-to-a-file-in-application-bundle), [and this](http://stackoverflow.com/questions/2502193/writing-nsdictionary-to-plist-in-my-app-bundle), [and this one as well](http://stackoverflow.com/questions/5853014/writing-into-a-file-objective-c), [and this one too](http://stackoverflow.com/questions/11016371/ios-i-cant-write-my-file). ***Now I ask: would it really have been so hard to find any of these?*** –  Jan 29 '13 at 19:18
  • You are right. I really apologise....! – Kostas Jan 29 '13 at 19:49

1 Answers1

2

You aren't allowed to write to the App directory. Try writing to the Documents directory inside that app folder.

NSString *data = @"testData";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"settings.txt"];
[data writeToFile:appFile atomically:YES];
James Webster
  • 31,873
  • 11
  • 70
  • 114
  • I am testing the application in Simulation Mode. Could you please tell me where is the Documents directory...? – Kostas Jan 29 '13 at 22:12