write NSString to file

file, ios, objective-c, xcode

Solution

`filename` is wrong. It should have the following format: `"directory/file.extension"`. You can use the methods `stringByAppendingPathComponent` and `stringByAppendingPathExtension` to construct such a string.

NSString *filename = [supportDirectory stringByAppendingPathComponent:[_nameTextField.text stringByAppendingPathExtension:@"txt"]];

Also, as a side note, the first line should be rewritten using `stringWithFormat` like this:

NSString *document = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", description, focus, level, equipment, waterDepth];

Problem

I'm trying to write a string to a file and store that in the applicationSupport folder within my app. But my NSLog() statement doesn't log anything in the debugger. I have tried to go through it with the debugger, and i can see that the content is nil, so i'm guessing that's why it's not outputting anything, but i don't know why it's set to nil. Can anybody see my mistake? ``` NSString *document = [[[[[[[[description stringByAppendingString:@" "]stringByAppendingString:focus]stringByAppendingString:@" "]stringByAppendingString:level]stringByAppendingString:@" "]stringByAppendingString:equipment]stringByAppendingString:@" "]stringByAppendingString:waterDepth]; //NSLog(@"%@", document); //get the documents directory: NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *supportDirectory = [paths objectAtIndex:0]; //filename NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory]; [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil]; NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil]; NSLog(@"%@", content); ```

Original source