orthehelper
orthehelper

Reputation: 4079

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.

this will help me for remote debug!

if any one can help me creating the file and save the data to it will be very use full

thanx

Upvotes: 3

Views: 3726

Answers (4)

Rafał Sroka
Rafał Sroka

Reputation: 40030

Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.

- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {

 NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];

 [[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

}

Usage:

NSString *stringWeWantToSave = @"This is an elephant";

NSString *fileName = [NSString stringWithString:@"savedString.txt"];

[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

Upvotes: 0

zaph
zaph

Reputation: 112857

You can save the files to the Documents directory, here is how to get the path to that directory:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

And a sample write statement:

NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

Upvotes: 4

Joe
Joe

Reputation: 57169

In the NSString documentation there is method called writeToFile:atomically:encoding:error:.

NSError *error;
[@"Write me to file" writeToFile:@"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];

Upvotes: 4

d.lebedev
d.lebedev

Reputation: 2303

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory

NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:@"myfile.txt"]
      atomically:YES encoding:NSUTF8StringEncoding error:&error];
 if (!succeed){
        // Handle error here }

source.

Upvotes: 2

Related Questions