NSTask 输出特殊字符转换为 UTF8

NSTask output special characters convert to UTF8

我 运行 通过 NSTask lsof,管道输出并读入 NSData。然后我用这个数据创建 NSString:

[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

我看到的问题是 NSTask 如何解释特殊字符。对于名称为:!@#$%^±^&*()ľščťžýáíé.docx 的文件 我得到这个结果:!@#$%^\xc2\xb1^&*()l\xcc\x8cs\xcc\x8cc\xcc\x8ct\xcc\x8cz\xcc\x8cy\xcc\x81a\xcc\x81i\xcc\x81e\xcc\x81.docx 看起来像是使用十六进制编码值的分解 UTF8。不幸的是,我找不到将其转换为正确的 UTF8 的方法。

我发现将环境变量 LC_ALL 设置为 en_US.UTF-8 就可以了。

[task setEnvironment:@{@"LC_ALL" : @"en_US.UTF-8"}];

对我有用。

    NSTask *task = [[NSTask alloc] init];
    NSMutableDictionary * e = [NSMutableDictionary dictionaryWithDictionary:[[NSProcessInfo processInfo] environment]];
    [e setObject:@"en_US.UTF-8" forKey:@"LC_ALL"];
    [e setObject:@"en_US.UTF-8" forKey:@"LANG"];
    [task setEnvironment:e];

在Swift中NSTaskProcess取代:

let process: Process = Process()
process.environment = ["LC_ALL": "en_US.UTF-8"]