Writing a string to a text file using Xcode for iPhone dev

I am trying to write a list to a text file that is included in my project (Deck.txt), the corresponding code is as follows:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Deck" ofType:@"txt"]; NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; deck = [[NSString alloc]initWithFormat: @"%@\n%@ %@",file, txtQuantity.text, cardName]; //[deck writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil]; [fileHandle writeData:[deck dataUsingEncoding:NSUTF8StringEncoding]]; [fileHandle closeFile]; 

When I run the code, it will not be saved in a text document, or at least not part of my project. Anyway, he will create a list and read from the file all the data that I am trying to write, but when I close the program, no changes are made to the text document. Any help would be most appreciated.

+6
objective-c iphone xcode
source share
3 answers

If you already have an instance of NSData, you can simply write the data to the built-in document directory on the device. With a little search, it’s not difficult to find a location when you start from the simulator to check.

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [paths objectAtIndex: 0]; NSString *docFile = [docDir stringByAppendingPathComponent: @"deck.txt"]; //your variable "deck" [deck writeToFile: docFile atomically: NO]; 

This will certainly be written to a file in the document directory. It should only be a matter of changing the code to read from the directory.

+16
source share

You cannot write files inside your bundle of packages. You want an NSDocumentDirectory.

+2
source share

configure your file path using this (as an example):

 NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/dt"]; 

then save the data as follows:

 [VARNAME writeToFile:filePath atomically:YES (or NO)]; 

I think that you are trying to do this the easiest.

+2
source share

All Articles