OperationQueue.main vs DispatchQueue.main

后端 未结 3 884
执笔经年
执笔经年 2021-02-01 15:33

When you need to perform something on the main thread in the completion block of a networking task or an operation, which of these ways to get it would be the most appropriate a

3条回答
  •  Happy的楠姐
    2021-02-01 15:57

    When to Use NSOperation

    The NSOperation API is great for encapsulating well-defined blocks of functionality. You could, for example, use an NSOperation subclass to encapsulate the login sequence of an application.

    Dependency management is the icing on the cake. An operation can have dependencies to other operations and that is a powerful feature Grand Central Dispatch lacks. If you need to perform several tasks in a specific order, then operations are a good solution.

    You can go overboard with operations if you are creating dozens of operations in a short timeframe. This can lead to performance problems due to the overhead inherent to the NSOperation API.

    When to Use Grand Central Dispatch

    Grand Central Dispatch is ideal if you just need to dispatch a block of code to a serial or concurrent queue.

    If you don’t want to go through the hassle of creating an NSOperation subclass for a trivial task, then Grand Central Dispatch is a great alternative. Another benefit of Grand Central Dispatch is that you can keep related code together. Take a look at the following example.

    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
    // Process Response
    ...
    
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        // Update User Interface
        ...
    })
    })
    

    In the completion handler of the data task, we process the response and update the user interface by dispatching a closure (or block) to the main queue. This is necessary because we don’t know which thread the completion handler is executed on and it most likely is a background thread.

    Quoted verbatim from this source

提交回复
热议问题