【问题标题】:Async call a method using IOS 4使用 IOS 4 异步调用方法
【发布时间】:2012-01-13 16:45:31
【问题描述】:

我想异步调用一个方法。这是一种从服务器获取 HTML 并将其设置为 UIWebView 的方法:

NSString *htmlTest = [BackendProxy getContent];
[webView loadHTMLString:htmlTest baseURL: nil];
[webView setUserInteractionEnabled:YES];

我想在数据获取期间在UIWebView 中启动一个活动指示器,所以我需要异步调用getContent。我怎样才能做到这一点?

【问题讨论】:

  • 请注意,方法不应以 get 为前缀,除非它们将值作为传递引用参数返回。就叫它content
  • 不是真名,只是为了这个例子,因为真名比较复杂=P。感谢您的建议

标签: ios asynchronous ios4


【解决方案1】:

这是 Apple 新的(ish)并发 API GCD 的一个很好的用例。

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^ {
    // Background work here
    NSLog(@"Finished work in background");
    dispatch_async(dispatch_get_main_queue(), ^ {
        NSLog(@"Back on main thread");
    });
});

这是dispatch queues上的文档

【讨论】:

  • 与 performSelectorInBackground:withObject 相比的优缺点?
  • @Tony 优点:更细粒度的控制,更简洁的代码(在我看来,我不喜欢一种方法的逻辑如此分散。)。缺点:在 iOS 4 之前无法使用。
【解决方案2】:

我建议NSObject 中的performSelectorInBackground:withObject:

像下面这样:

- (void)loadIntoWebView: (id) dummy
{

    NSString *html = [BackendProxy getContent];
   [self performSelectorOnMainThread: @selector(loadingFinished:) withObject: html];
}


- (void)loadingFinished: (NSString*) html
{
   // stop activity indicator
   [webView loadHTMLString:html baseURL: nil];
   [webView setUserInteractionEnabled:YES]; 
}

- (void) foo
{
   // ...
   // start activity indicator
   [self performSelectorInBackground: @selector(loadIntoWebView:) withObject: nil];
}

【讨论】:

  • 你投反对票的速度太快了。在您发表评论前一分钟,我意识到并修复了它。
  • performSelectorInBackground 返回一个 EXC_BAD_INSTRUCTION。有什么帮助吗?
  • 这是一个错误 loadIntoWebview!= loadIntoWebView。我会编辑你的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多