I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.
Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.
NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
And to retrieve the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With