使用 IOS 4 异步调用方法

发布于 2024-12-27 01:15:16 字数 328 浏览 0 评论 0原文

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

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

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

I want to call a method asynchronically. It's a method that gets HTML from a server and sets it to a UIWebView:

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

I want to start an activity indicator in the UIWebView during the data fetch, so I need to call getContent asynchronically. How can I achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花想c 2025-01-03 01:15:16

这是 Apple 新的并发 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");
    });
});

这是关于 调度队列

This is a great use case for GCD, Apple's new(ish) concurrency API.

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");
    });
});

Here's the documentation on dispatch queues

硪扪都還晓 2025-01-03 01:15:16

我建议使用NSObjectperformSelectorInBackground: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];
}

I suggest performSelectorInBackground:withObject: of NSObject.

Like the following:

- (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];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文