【问题标题】:CompletionHandler Behavior on Main vs Background thread主线程与后台线程上的 CompletionHandler 行为
【发布时间】:2021-05-19 02:13:31
【问题描述】:

在完成处理程序方面,使用方法的线程是否重要?在主线程上运行时,我没有问题; (data) incompletionHandler 被调用,因此函数的 completionHandler 在其中。

以下是我的代码:

  static func getInfo(user: User,completion: (([String:String]) -> Void)? = nil){
      
       print(user.apiUid)
       var enrolledCourses: [String:String] = [:]
       
       NetworkingManager.staticGeneralRequest(withEndpoint: someURL, oauthToken: user.oauth_token, oauthTokenSecret: user.oauth_token_secret) { (data) in
           let decodedData: [String:String] = data.getData()
           completion?(decodedData)
       }
     
   }

//NOTE: According to the compiler, 
//the use of an optional completionHandler means that it's `@escaping` by default.

这是与线程相关的问题吗?有哪些最佳实践可以确保代码在线程间正常运行?

【问题讨论】:

    标签: ios swift multithreading completionhandler


    【解决方案1】:

    在您收到响应之前,您的闭包已被解除分配。像这样添加@escapingstatic func getInfo(user: User, completion: @escaping (([String:String]) -> Void)? = nil) 以使其保持在范围内。

    【讨论】:

    • 我试过了,但我得到一个错误:Closure is already escaping in optional type argument。这意味着它已经是@escaping
    • 您能在 NetworkingManager 类中显示更多代码吗?
    • 当然,一秒钟
    • 我解决了这个问题;我是在一个非常规的环境中打电话的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2012-12-31
    • 2011-10-24
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多