Re: Best way to save a simple text file?
Re: Best way to save a simple text file?
- Subject: Re: Best way to save a simple text file?
- From: Douglas Davidson <email@hidden>
- Date: Fri, 16 Nov 2007 10:25:00 -0800
On Nov 16, 2007, at 10:02 AM, Jean-Nicolas Jolivet wrote:
What would be the best way to save a simple NSString to a text file
in a document based application?
Right now I am using the following (in writeToUrl:ofType:error
method):
---------------------------------------------
NSData *data = [NSData dataWithBytes: [myString UTF8String] length:
[myString length]];
BOOL writeSuccess = [data writeToURL:inAbsoluteURL atomically:NO];
---------------------------------------------
However, I was wondering... is it really necessary for me to convert
my string to an NSData object before saving it? Isn't there any
other way to do it? Also, what if I would like to support multiple
languages (i.e. multiple encoding??)... right now the string is
converted to UTF8...
The best way to save a string to a text file is to use -[NSString
writeToURL:atomically:encoding:error:], or the corresponding method
taking a path. This is even more important on Leopard, because on
Leopard NSString will tag the file with an extended attribute
specifying the encoding, so that it can be opened properly by TextEdit
and anything else using Cocoa APIs to load text files. Take a look at
the TextEdit source on Leopard for example usage in a document-based
application.
If you happen to need the contents of a string converted into an
NSData in a particular encoding, rather than a file, you can use -
[NSString dataUsingEncoding:] instead of copying twice.
However, please don't think that you need multiple encodings to
support multiple languages; Unicode encodings (in particular, UTF-8
and UTF-16) are sufficient for any language you are likely to
encounter. Other encodings should be used only if necessary to
support legacy data and protocols.
Douglas Davidson
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden