将UTF-16文件读入核心数据

时间:2011-08-11 03:08:25

标签: iphone ios ipad core-data utf-16

我有一个包含Tamil字符的utf-16的csv文件,并且在查看时显示正常。我将它读入我的iphone / ipad程序并从中创建核心数据库。我遇到的问题是信息以另一个字符集存储在核心数据库中。在从csv构建数据库时,如何指定使用UTF16StringEncoding?这是我的加载方法:

- (void)setupQuestions {
NSString *paths = [[NSBundle mainBundle] resourcePath];
NSString *bundlePath = [paths stringByAppendingPathComponent:@"questions_tm.csv"];
NSString *dataFile = [[NSString alloc] initWithContentsOfFile:bundlePath];
NSArray *dataRows = [dataFile componentsSeparatedByString:@"\n"];
[dataFile release];

//Question *card;
for (int i = 0 ; i < [dataRows count] ; i++)
{
    NSArray *dataElements = [[dataRows objectAtIndex:i] componentsSeparatedByString:@","];
    if ([dataElements count] >= 1)
    {
        card = (Question *)[NSEntityDescription insertNewObjectForEntityForName:@"Question" inManagedObjectContext:[self managedObjectContext]];
        NSLog(@"Row ID: %i", i);
        card.ID = [NSNumber numberWithInt:i];
        card.answer = [NSNumber numberWithInt:[[dataElements objectAtIndex:1] intValue]];
        card.question = [dataElements objectAtIndex:2];
        card.optionA = [dataElements objectAtIndex:3];
        card.optionB = [dataElements objectAtIndex:4];
        card.optionC = [dataElements objectAtIndex:5];
        card.optionD = [dataElements objectAtIndex:6];


        [self save];
    }
}

}

1 个答案:

答案 0 :(得分:0)

假设card.questionNSString中您想要的UTF16StringEncoding,您至少有以下两个选项:

NSString* question = [dataElements objectAtIndex:2];
const char * questionCString = [question cStringUsingEncoding:NSUTF16StringEncoding];
card.question = [[[NSString alloc] initWithCString:questionCString encoding:UTF16StringEncoding] autorelease];

选项2:

NSString* question = [dataElements objectAtIndex:2];
NSData* questionData = [question dataUsingEncoding:NSUTF16StringEncoding];
card.question = [[[NSString alloc] initWithData:questionData encoding:UTF16StringEncoding] autorelease];