(226) Advanced NSOperations

NSOperations are now the technology that the iOS, OS X and Watch apps rely on to perform responsive,

WWDC app

    1. Core Concepts
      1. NSOperationQueue
        1. high level dispatch_queue_t
        2. make it easy to cancel any operation !
        3. maxConcurrentOperationCount = 1 -> serial queue
        4. maxConcurrentOperationCount = Default // as many as system allows
      2. NSOperation
        1. high level dispatch_block_t
        2. long-running task // milli-seconds to minutes
        3. subclass-able:
        4. start in pending-state
        5. pending -> ready -> executing -> finished 
        6. Can be CANCELLED anytime before finish !!! // cancel()
        7. Cancelling: observe the cancelled:Bool value and handle accordingly (rollback etc..)
        8. Cancelling: susceptible to race condition // has to be not-finished YET!
    2. Beyond basics
      1. Readiness & Dependencies
        1. Without Dependencies -> any ready operation can be executed (no order)
        2. Not limited by Queues ! // operationB.addDependency(operationA)
        3. Operation Deadlock // Dependency loop
      2. Abstraction of logic
      3. UI Operations:  UI can be put inside NSOperation !
        1. Authentication operation
        2. Watch video operation
        3. Alert
        4. Modal UI
      4. NSBlockExecution: execute blocks inside NSOperation!
      5. Composing Operations: nested Operations
        1. Downloading + Parsing = Import
        2. Dynamically create a Query inside a query and execute recursively !
      6. Mutual Exclusivity: only 1 operation of that kind to run at a time
        1. Alerts: only see 1 alert of a time // make the second alert dependent on 1st
        2. Videos: only watch 1 video at a time
        3. As long as the 2nd depends on the 1st -> mutually exclusive !
    3. Sample code
      1. Earthquakes & Operations
      2. Operation Observers: notified about events in operation’s lifecycle
        1. Operation start, end, generation
        2. Examples observers:
          1. Timeouts: cancel if run out of time
          2. Background: when app goes to background -> automatically start !
          3. Network activity indicator: retain the Indicator when begins & release when ends

Summary

Lots of cool stuffs can be done with NSOperations. The main output from this video is how to use Dependency to setup order between tasks.

A question in regard to real Mutual Exclusivity using Dependency: we can only do that if an order can be established, but what to do in case no specific order exists?

Advertisements