title: NSOperation with a delay - is it async or sync?
body: <p>I'm creating an <code>NSOperation</code> that executes a closure with a delay. The operations are added into a queue, every time before a new operation is added I cancel all existing ones in the queue:</p>
  <pre class="lang-swift prettyprint-override"><code>let myOp = SomeOperation { [weak self] in /* do something */ }
  queue.cancelAllOperations()
  queue.addOperation(myOp)
  </code></pre>
  <h3>Operation Code 1</h3>
  <pre class="lang-swift prettyprint-override"><code>final class SomeOperation: Operation {
  
      private let closure: () -&gt; Void
  
      init(closure: @escaping () -&gt; Void) {
          self.closure = closure
      }
  
      override func main() {
          if isCancelled {
              return
          }
          DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: doSomething)
      }
  
      private func doSomething() {
          guard isCancelled == false else {
              return
          }
          closure()
      }
  }
  </code></pre>
  <p>While the above code works, the code below doesn't. In the <code>DispatchQueue</code> closure, <code>self</code> is <code>nil</code>:</p>
  <h3>Operation Code 2</h3>
  <pre class="lang-swift prettyprint-override"><code>final class SomeOperation: Operation {
  
      private let closure: () -&gt; Void
  
      init(closure: @escaping () -&gt; Void) {
          self.closure = closure
      }
  
      override func main() {
          if isCancelled {
              return
          }
          DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
              guard let self = self else { return }
              guard isCancelled == false else { return }
              self.closure()
          }
      }
  }
  </code></pre>
  <p>So I'm trying to learn a bit deeper:</p>
  <ol>
  <li>In Code 2, <code>self</code> is <code>nil</code> because as soon as <code>DispatchQueue.main.asyncAfter…</code> is called, the <code>main</code> method finishes and the operation is thus released.</li>
  <li>Code 1 works because <code>execute: doSomething</code> implicitly captures/retains a <code>self</code>, so even after <code>asyncAfter</code>, <code>self</code> is still there.</li>
  </ol>
  <p>So my questions are:</p>
  <ol>
  <li>In Apple's doc it says for concurrent operations I should rather be using <code>start</code>, <code>asynchronous</code>, <code>executing</code>, <code>finished</code>, etc. In my case I just need to have a delay, not actually doing anything asynchronous, should I do it in <code>main</code> only or should I do it as an async operation by implementing those methods Apple suggested?</li>
  <li>Is my thinking correct that in Code 1 there's a <code>self</code> retained implicitly, which doesn't sound correct and can create retain cycle?</li>
  </ol>
  <p>Thanks!</p>