【问题标题】:Objective C method not waiting for Swift method's completion handler目标 C 方法不等待 Swift 方法的完成处理程序
【发布时间】:2020-07-29 21:14:46
【问题描述】:

我正在从一个 Objective C 类中调用一个 Swift 方法。它应该运行 Swift 代码,等待它完成,然后才继续到 Objective C 类的下一行。现在它正在运行几行 Swift 代码,然后转到完成处理程序之后的行,在完成处理程序被命中之前。当 Swift 代码完成运行时,它会按原样到达完成处理程序,但是我如何阻止它提前跳到完成处理程序之前呢?

Swift 类 (TwitterRequest.swift)

@objc func startRequest(withUsername username: String, completion: @escaping (Bool) -> Void) {
        
        requestToken() { token in
            
            self.getUserTimeline(bearerToken: token, username: username) { timeline in
                // Get user twitter feed
                completion(true)
            }
        }
        
    }

从 Objective C 类调用上述方法

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showTwitterTimeline"]) {
    
        [[TwitterRequest new] startRequestWithUsername:_usernameTextField.text completion:^(BOOL completion) {

         // Completion handler for startRequest. 

        }];

         
         // Code is jumping here before above completion handler is hit. Why?
    }
}




func getUserTimeline(bearerToken: BearerToken, username: String, completion: (UserTimeline) -> Void) {

        var test = UserTimeline()
        
        completion(test)
}

【问题讨论】:

  • 了解异步编程的含义:programmingios.net/what-asynchronous-means
  • 我现在明白 URLSession 请求是异步的。使用信号量等待请求发出会不会是个坏主意?
  • 是的,这是个坏主意,因为您会阻塞主 (UI) 线程(因为这是在 prepareForSegue 中完成的)。如果您希望在请求完成后发生某些事情,则必须将其放入完成处理程序块中。

标签: ios objective-c swift closures


【解决方案1】:

这是完成处理程序的预期行为。您的代码继续执行,但是当您的请求完成其工作时,将调用此请求的完成处理程序。

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    相关资源
    最近更新 更多