如何可靠地将未知编码的文本文件拉入 iPhone 上的 NSString 中?
这是我用来将文本文件拉入名为 textView
的 UITextView
中的一些代码。
因为我无法总是提前知道文件的编码,所以我使用方法 -stringWithContentsOfFile:usedEncoding:error:
,它通过引用存储编码值。
获得编码后,我将打开该文件,如果出现错误,则打印出一些信息:
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;
在 iPhone 上,如果文件是 UTF8 编码的,文本视图将显示文件的内容适当地。
在 iPhone 上,如果文件是 ASCII 编码的 (NSASCIIStringEncoding
),那么我会得到一个奇怪的字符串编码值:
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
对于 NSASCIIStringEncoding
我应该得到值为 1,而不是 805298632。
不同的是,如果我通过模拟器打开文件,我会得到正确的编码值,并且文本视图会显示 ASCII 编码文件的内容。
我认为我的语法是正确的,但我想我错过了一些可能很明显的东西。我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
%lx
。NSStringEncoding
是一个NSUInteger
,它是设备上的一个unsigned long
。一些枚举值是十六进制值。_textEncoding
初始化为 0。枚举常量从 1 开始。%lx
.NSStringEncoding
is anNSUInteger
which is anunsigned long
on the device. Some of the enumerated values are hex values._textEncoding
to 0. Enumerated constants start at 1.