Re: Opening old text files with non-deprecated stringWithContentsOfFile calls?
Christiaan Hofman <[email protected]> Tue, 12 Oct 2010 19:06:21 +0200
| Newsgroups | gmane.comp.macosx.devel |
|---|---|
| Message-ID | <[email protected]> |
On Oct 12, 2010, at 17:54, Joar Wingfors wrote: > > On 12 okt 2010, at 07.44, Michael Dupuis wrote: > >> Any of the files downloaded here will cause issues: http://www.grassrootsrecipes.com/ >> >> When I open them in TextWrangler, it appears that these are "Western (MacOS) with Windows (CRLF), at least that is what's displayed at the bottom. If I just download one and try and read it in even using the >> >> + (id)stringWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error >> >> call, it will fail. If I fallback to using the deprecated call, I can open it, so the deprecated call is doing SOMETHING that works, I just haven't been able to figure out what that is. > > > Don't use that method to initialize the string, use: > > + (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error > > The method you use tries to figure out the encoding used - an impossible task for the most part. > > The deprecation of initializers was intended to force the developer to provide an encoding to use - so you need to do that. If you have reason to believe that these strings are encoded in "Western (MacOS)", then provide that (I think that's NSISOLatin1StringEncoding). > > j o a r > Actually, "Western (MacOS)" is NSMacOSRomanStringEncoding. But as the files have windows line endings, and the fils also open with "Western (ISO Latin)" encoding, I do expect that they're using with the latter (which is NSISOLatin1StringEncoding, and the standard on Windows). So even though TextWrangler is able to open the file, it seems to do so with the wrong encoding, and potentially incorrectly representing the data. This also illustrated why guessing the encoding in general simply does not work, it's just hit-and-miss, usually miss, and why you should usually just use a fixed encoding as JOAR says. As for the comparison to the deprecated method: it may well be that the old and new guessing methods use slightly different guesses, but that does not mean that one is better than the other, they're both more wrong than right. I would expect that even for these samples the deprecated method may be able to read the text, I am convinced it would just as well be possible to find a set of samples for which this works in the opposite direction. Christiaan