Advertisement
nanosem

Untitled

May 23rd, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.32 KB | None | 0 0
  1. No, there are definitely times where you would not want to use [unowned self]. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called.
  2.  
  3. Example: Making an asynchronous network request
  4.  
  5. If you are making an asynchronous network request you do want the closure to retain self for when the request finishes. That object may have otherwise been deallocated but you still want to be able to handle the request finishing.
  6.  
  7. When to use unowned self or weak self
  8.  
  9. The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.
  10.  
  11. Difference between unowned and weak
  12.  
  13. The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement