views:

484

answers:

3

How do I save an NSString as a .txt file on my apps local documents directory (UTF-8)?

A: 

you could use NSUserDefaults

Saving:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

Reading:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
Alexandergre
Dude, .txt file
RexOnRoids
+2  A: 
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
}
Vladimir
Don't pass `nil` for the `error:` argument. For one thing, it's the wrong type (`nil` is conceptually an `id`, whereas the `error:` argument is an `NSError **`, which is basically an `id *`); the constant of the proper type is `NULL`. More importantly, when this statement fails, don't you want to know why?
Peter Hosey
Progress, but you also should not assume that `error` is `nil` when the message succeeds. Test whether the message returned `YES` or `NO`, and only examine the error object when it returns `NO`. Citation: http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-SW1 (first “important” sidebar—admittedly, it's a little oblique about it)
Peter Hosey
Thanks for your comments
Vladimir
+1  A: 

Something like this:

NSString *homeDirectory;
homeDirectory = NSHomeDirectory(); // Get app's home directory - you could check for a folder here too.
BOOL isWriteable = [[NSFileManager defaultManager] isWritableFileAtPath: homeDirectory]; //Check file path is writealbe
// You can now add a file name to your path and the create the initial empty file

[[NSFileManager defaultManager] createFileAtPath:newFilePath contents:nil attributes:nil];

// Then as a you have an NSString you could simple use the writeFile: method
NSString *yourStringOfData;
[yourStringOfData writeToFile: newFilePath atomically: YES];
cp21yos