【问题标题】:Grand Central Dispatch (GCD) and asynchronous APIsGrand Central Dispatch (GCD) 和异步 API
【发布时间】:2023-03-07 13:53:02
【问题描述】:

我正在使用 Twitter API 发布推文。有时这可能需要一些时间,所以我想在后台执行“推文发布”操作。为此,我正在使用 GCD,如下所示:

- (void)myClassMethodToPostTweet {
    dispatch_async(network_queue, ^{
        // … construct the tweet message
        NSString *tweet = @"…";

        // … check if network is available
        [self isConnectedToWeb];

        // … initialize twitter API
        TwitterAPIClass *twitterAPI = [[[TwitterAPIClass alloc] init…] autorelease];
        twitterAPI.delegate = self;
        twitterAPI.APIKey = ...;
        twitterAPI.APISecret = ...;

        // … use twitter API to post the tweet
        [twitterAPI postTweet:tweet];
    });
}

...
/* and when the API reports a successful operation, update the required variables and UI */
...

- (void)twitterAPIDelegateMethodReportingOperationSuccess {
    // … update any variables/records

    // … update UI
    dispatch_async(dispatch_get_main_queue(), ^{
        // … UI updation code
    });
}

问题是,我没有收到委托回调!我错过了什么?

【问题讨论】:

标签: iphone asynchronous event-handling objective-c-blocks grand-central-dispatch


【解决方案1】:

您是否尝试在主线程上运行 Twitter 连接?如果它在主线程上运行而不是在某些后台队列上运行,您可能遇到了NSURLConnection 的运行循环问题。 (只是一个疯狂的猜测。)

【讨论】:

  • +1 这是一个运行循环问题。 MGTwitterEngine 使用 NSURLConnection 的异步 API 进行通信,这需要一个 runloop。我怀疑您是否可以在不对代码进行一些重大更改的情况下使其与 GCD 一起使用。 GCD 不适用于基于运行循环的通信。
  • 那么,我还有哪些其他选择? NSOperation 会完成这项工作吗? (不过,我对此表示怀疑,因为它在后台使用 GCD)
  • Twitter 库没有为您提供异步接口?这似乎是一个自然的选择,因为它显然已经使用了异步NSURLConnection。您在问题中给我们的代码示例看起来足够异步。它会在某个地方阻塞吗?
  • 嗯,不是真的!这是对 [self isConnectedToWeb] 的调用;这实际上阻塞了主线程,但我想我可以解决这个问题。实际上,我尝试将 Twitter API 调用包装到 dispatch_async(dispatch_get_main_queue(), ^{ ... });也可以解决运行循环问题,但我遇到了崩溃问题。奇怪的是,我只有一个 Twitter 帐户遇到了这个问题。 仍然不知道为什么!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 2011-07-28
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多