2 daffodilgirl DaffodilGirl 于 2012.12.18 14:51 提问

objectiveC中怎么获得所有的可用编码?

在Java中可以这样获取可用编码:

SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
Vector allEncodes = new Vector();
for (Map.Entry<String, Charset> entry : availableCharsets.entrySet()) {
            allEncodes.add(entry.getKey());
}

然后这样读取文件:

Reader in = new InputStreamReader(new FileInputStream(aPath), allEncodes.get(0) );

那么在objective-c中怎么实现类似的功能?

2个回答

redCoral_
redCoral_   2012.12.18 16:15
已采纳

我给的代码有点类似Java.不过你要完善其中的readingError变量。核心代码是avaiableStringEncodings.

  NSMutableArray *arrayOfEncodings = [[NSMutableArray alloc] init];

  const NSStringEncoding *encodings = [NSString availableStringEncodings];
  while (*encodings != 0){
    [arrayOfEncodings addObject:[NSNumber numberWithInt:*encodings]];
    encodings++;
  }

  NSError *readingError = nil;
  NSString yourPath = @"some path you want";
  NSData *data = [[NSData alloc] initWithContentsOfFile:yourPath    options:NSDataReadingUncached error:&readingError];

  NSStringEncoding firstEncoding = (NSStringEncoding) [((NSNumber *) [arrayOfEncodings objectAtIndex:0]) intValue];

  NSString *myString = [[NSString alloc] initWithData:data encoding:firstEncoding]; 
gaoXxxing
gaoXxxing   2012.12.18 15:44
const NSStringEncoding* encodingArray = [NSString availableStringEncodings];
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!