How do I write a simple string to a file on the iphone?
Simple qu开发者_如何转开发estion:
I have a large string that I want to write to a file in the docs folder for an app. How do I do a simple file creation/write?
If you have an NSString
, you can do
NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];
[myString writeToFile:path atomically:YES];
Look at NSString
's writeToFile:atomically:encoding:error:
method. Usage looks like this:
[myString writeToFile:myPath atomically:YES encoding:NSUTF8StringEncoding error:&myError];
NSError *error = nil;
[@"foo bar baz" writeToFile:@"someFileName" atomically:NO encoding:NSUTF8StringEncoding error:&error];
精彩评论