Question

I have text files that contain some basic data that I need for my app. I can read the files and I get the file path with:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Money" ofType:@"txt"];

To write to the file I would think I would use:

[[HoldString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];

This does not work though, I have also tried geting the file path with:

NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileAtPath = [filePath stringByAppendingPathComponent:@"Money.txt"];

None of these work. I would like to be able to read from the file not using CoreData.

Was it helpful?

Solution

You can't write to paths that are inside your app bundle; your bundle is readonly. So that's why the first approach won't work.

But your second approach should in fact work to form a valid path in the documents directory. Are you sure there's something there to read? That directory will be empty when your app is installed. If you want to modify a text file that you yourself include, first copy it from the bundle path to the documents folder.

OTHER TIPS

The resource bundle of an app is read-only (at least on a real device). You need to write your data to another location such as the Documents directory.

Most apps check to see if the file exists in the Documents directory. If not, it copies a file from the resource bundle. Then all reading and writing is done to the copy.

On iOS the application bundle is readonly, so you can't write on it. A way to go around this is to use the documents folder to store the files that you need and write data there.

In your case an alternative would be to use NSUserDefaults. So the first time that the application runs you can read from that file (Money.text) on the bundle (or avoid holding it on the bundle if you can do so). After reading it, instead of writing to it, you save the whole text to NSUserDefaults like this:

[[NSUserDefaults standardUserDefaults] setObject: holdString forKey: @"money" ];  // By convention you should name it holdString instead of HoldString.  

To read data:

NSString* moneyStr= [[NSUserDefaults standardUserDefaults] objectForKey: @"money"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top