2

问题陈述

我创建了许多字符串,将它们连接成 CSV 格式,然后将字符串作为附件通过电子邮件发送。

当这些字符串仅包含 ASCII 字符时,将正确构建 CSV 文件并通过电子邮件发送。当我包含非 ASCII 字符时,结果字符串格式不正确,并且 CSV 文件未正确创建。(电子邮件视图显示附件,但未发送。)

例如,这有效:

uncle bill's house of pancakes

但这不是(注意卷曲撇号):

uncle bill’s house of pancakes

问题

如何正确创建和编码最终字符串,以便包含所有有效的 unicode 字符并正确形成结果字符串?

笔记

  • 字符串是通过 UITextField 创建的,然后写入核心数据存储区,然后再从核心数据存储区读取。

  • 这表明问题在于字符串的初始创建和编码:NSString unicode encoding problem

  • 我不想这样做:在objective-c中从NSString中删除非ASCII字符

  • 字符串被写入数据存储并从数据存储中读取。字符串在应用程序的表格视图中正确(单独)显示。该问题仅在将电子邮件附件的字符串连接在一起时才会出现。

字符串处理代码

我像这样将我的字符串连接在一起:

[reportString appendFormat:@"%@,", category];
[reportString appendFormat:@"%@,", client];
[reportString appendFormat:@"%@\n", detail];
etc.

用无聊的引号替换大引号使其工作,但我不想这样做:

- (NSMutableString *)cleanString:(NSString *)activity {
    NSString *temp1 = [activity stringByReplacingOccurrencesOfString:@"’" withString:@"'"];
    NSString *temp2 = [temp1 stringByReplacingOccurrencesOfString:@"‘" withString:@"'"];
    NSString *temp3 = [temp2 stringByReplacingOccurrencesOfString:@"”" withString:@"\""];
    NSString *temp4 = [temp3 stringByReplacingOccurrencesOfString:@"“" withString:@"\""];
    return [NSMutableString temp4];
}

编辑: 电子邮件已发送:

    NSString *attachment = [self formatReportCSV];
    [picker addAttachmentData:[attachment dataUsingEncoding:NSStringEncodingConversionAllowLossy] mimeType:nil fileName:@"MyCSVFile.csv"];

whereformatReportCSV是连接并返回 csv 字符串的函数。

4

1 回答 1

4

您似乎遇到了字符串编码问题。在没有看到您的核心数据模型是什么样子的情况下,我认为问题归结为以下代码重现的问题。

NSString *string1 = @"Uncle bill’s house of pancakes.";
NSString *string2 = @" Appended with some garbage's stuff.";
NSMutableString *mutableString = [NSMutableString stringWithString: string1];
[mutableString appendString: string2];
NSLog(@"We got: %@", mutableString);
// We got: Uncle bill’s house of pancakes. Appended with some garbage's stuff.

NSData *storedVersion = [mutableString dataUsingEncoding: NSStringEncodingConversionAllowLossy];
NSString *restoredString = [[NSString alloc] initWithData: storedVersion encoding: NSStringEncodingConversionAllowLossy];
NSLog(@"Restored string with NSStringEncodingConversionAllowLossy: %@", restoredString);
// Restored string with NSStringEncodingConversionAllowLossy: 

storedVersion = [mutableString dataUsingEncoding: NSUTF8StringEncoding];
restoredString = [[NSString alloc] initWithData: storedVersion encoding: NSUTF8StringEncoding];
NSLog(@"Restored string with UTF8: %@", restoredString);
// Restored string with UTF8: Uncle bill’s house of pancakes. Appended with some garbage's stuff.

请注意第一个字符串(使用 ASCII 编码)如何无法处理非 ASCII 字符的存在(如果dataUsingEncoding:allowsLossyConversion:与第二个参数一起使用它可以YES)。

这段代码应该可以解决这个问题:

NSString *attachment = [self formatReportCSV];
[picker addAttachmentData:[attachment dataUsingEncoding: NSUTF8StringEncoding] mimeType:nil fileName:@"MyCSVFile.csv"];

注意:如果您需要处理日语等非 UTF8 语言,您可能需要使用其中一种 UTF16 字符串编码。

于 2013-04-18T09:22:10.237 回答