views:

92

answers:

1

Here is some code which I use to pull a text file into a UITextView called textView.

Because I can't always know the file's encoding ahead of time, I use the method -stringWithContentsOfFile:usedEncoding:error:, which stores an encoding value by reference.

Once I have the encoding, I then open up the file and, if there's an error, print out some information:

NSError *_error = nil; 
NSStringEncoding _textEncoding;
NSString *_contentText = [NSString stringWithContentsOfFile:[baseURL path] usedEncoding:&_textEncoding error:&_error];

if (_error) {
    NSLog(@" _error: %@", [_error userInfo]);
    NSLog(@" _textEncoding: %d", _textEncoding);
}

textView.text = _contentText; 

On an iPhone, if the file is UTF8-encoded, the text view displays the file's contents properly.

On an iPhone, if a file is ASCII-encoded (NSASCIIStringEncoding), then I get a strange string encoding value:

2010-07-23 02:57:46.786 App[9160:307]  _error: {
    NSFilePath = "/var/mobile/Applications/0AD83E02-7A2A-4665-8B8F-17E03EE12B9E/Documents/A+B.txt";
}
2010-07-23 02:57:46.791 App[9160:307]  _textEncoding: 805298632

For NSASCIIStringEncoding I should get a value of 1, not 805298632.

The twist is that, if I open the file through the Simulator, I get the correct encoding value and the text view displays the ASCII-encoded file's contents.

I think I have the correct syntax, but I guess I have missed something, possibly obvious. What am I doing wrong here?

A: 
  1. The stringWithContentsOfFile:usedEncoding:error: is failing. Log the error details to determine why.
  2. The format specifier should be %lx. NSStringEncoding is an NSUInteger which is an unsigned long on the device. Some of the enumerated values are hex values.
  3. What platform is the file being created on? Are you positive that the encoding is actually ASCII? You will need to do a hexdump on the file to verify if the encoding is valid.
  4. Try initializing _textEncoding to 0. Enumerated constants start at 1.
  5. Add a guard to test that the string returned is not nil before passing to the view. As per the documentation the return is nil if there was an error.
falconcreek