write NSString to file

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);

Upvotes: 2

Views: 6127

Answers (3)

Alex
Alex

Reputation: 31

You have wrong initialize filename. It should be:

  NSString *filename = [NSString stringWithFormat:@"%@/%@", supportDirectory,[_nameTextField.text stringByAppendingString:@".txt"]];

it will works! Good luck:)

Upvotes: 0

sch
sch

Reputation: 27536

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];

Upvotes: 6

Lefteris
Lefteris

Reputation: 14687

The

NSString *filename = [NSString stringWithFormat:[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory];

is wrong. It should be:

NSString *filename = [NSString stringWithFormat:"%@%@",[_nameTextField.text stringByAppendingString:@".txt"], supportDirectory];

Upvotes: -4

Related Questions