NSAttributedString initWithData:options:documentAttributes:error:执行速度非常慢

时间:2013-10-05 13:11:06

标签: ios webkit nsattributedstring

我正在尝试新的iOS 7 API,以下代码需要一分钟才能执行!

NSLog(@"start encoding");
NSString *htmlBody = @"<html><body>I am <b>bold</b> and <i>italic</i>";
NSStringEncoding encoding = NSUnicodeStringEncoding;
NSData *data = [htmlBody dataUsingEncoding:encoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                          NSCharacterEncodingDocumentAttribute: @(encoding)};

NSAttributedString *body = [[NSAttributedString alloc] initWithData:data
                          options:options
                          documentAttributes:nil
                          error:nil];

NSLog(@"end encoding%@", body);

发生了什么事?

1 个答案:

答案 0 :(得分:7)

在做了一些调查之后,我意识到我把这个方法称为webview的公园.finishLoading回调。我相信这会导致某些实时锁定或等待WebKit的线程。解决方案是让webview方法从dispatch_aync块中调用其委托(或其他代码):

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (self.successBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //this success block eventually calls my NSAttributedString code above
             self.successBlock();     
        }); 
    }
}