【问题标题】:Re-encoding a NSString returns null重新编码 NSString 返回 null
【发布时间】:2010-10-05 09:42:46
【问题描述】:

所以我有这段代码:

if ([receivedPage hasPrefix:[NSString stringWithUTF8String:"\xC3\xAF\xC2\xBB\xC2\xBF"]]) // UTF-8 BOM 'EF BB BF' as UTF-16 chars
    {
        //DebugLog(@"converting calls list to UTF8");
        receivedPage = [[[NSString alloc] initWithData:[receivedPage dataUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] autorelease];
    }

但有时当 if 为真时,receivedPage 变为空。为什么会这样?

接收到的页面就是这个函数的返回值:

 NSURLResponse * response;
    NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];

    if ([result length] > 0)
        return [[[NSString alloc] initWithBytes: (const void*)[result bytes] length:[result length] encoding: encoding] autorelease];
    else
    {
        if (error && *error)
            DebugLog(@"URL request got error: %@",*error);
        return nil;
    }

这里的编码是NSISOLatin1StringEncoding(不知道为什么,我在调试别人的代码)。

知道为什么会这样吗?

【问题讨论】:

    标签: cocoa encoding nsstring


    【解决方案1】:

    您似乎正在尝试将字符串(包含字符的对象)视为数据(包含字节的对象)。保留您从连接中收到的数据,并检查其中的 UTF-8 BOM(正确的三字节版本),然后根据您是否找到它使用NSUTF8StringEncodingNSISOLatin1StringEncoding

    或者,只要有条件地使用 UTF-8,如果您可以修复服务器也这样做。

    另外,您可能应该切换此代码以异步使用 NSURLConnection。如果用户的 Internet 连接速度很慢,那么您将在此处挂起您的应用程序。异步执行此操作可让您保持 UI 运行、在适当时显示进度并允许用户取消。

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      相关资源
      最近更新 更多