开发者

Reading a UTF-16 file into core data

开发者 https://www.devze.com 2023-03-27 12:09 出处:网络
I have a csv file that is utf-16 containing Tamil characters and displays fine as I view it.I read it into my iphone/ipad program and creates a core data database from it.The problem I have is that th

I have a csv file that is utf-16 containing Tamil characters and displays fine as I view it. I read it into my iphone/ipad program and creates a core data database from it. The problem I have is that the information gets stored in the core database in another character set. How do I specify to use UTF16StringEncoding while I build the database from the csv? Here is my loading method:

- (void)setupQuestions {
NSString *paths = [[NSB开发者_开发知识库undle 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];
    }
}

}


Assuming card.question is the NSString you want in UTF16StringEncoding, you have at least the following two options:

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

Option 2:

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

精彩评论

暂无评论...
验证码 换一张
取 消