Vanishadow
Vanishadow

Reputation: 43

swift closure pass by reference?

I am having trouble to understand how the closure is created.

For example in ViewController A:

dispatch_async(dispatch_get_main_queue()) [weak weakSelf = self] {              
  weakSelf?.property = "something"
}

I am guess how this code work

1) ViewController A just create a closure (let say the closure is stored in heap address :0) and attach a strong reference to the closure

2) the object in the main queue also has another strong reference to the closure since the memory pointer is being pass by the function in ViewController A

3) when ViewController A is dealloc before gcd calls the closure , the closure object is still in the heap since gcd has a strong reference to it, but i don't understand that when the ViewController is nil, how would gcd calls the closure in ViewController A?

am i misunderstood something?

Upvotes: 2

Views: 1005

Answers (1)

matt
matt

Reputation: 535547

The closure is not "in" ViewController A. You say "ViewController A ... attach a strong reference to the closure" but there is no strong reference in the code you show. Calling dispatch_async hands the closure over to GCD, which retains it and places it onto the queue for later execution.

At the time that it is executed, either the reference to weakSelf points to the ViewController A (because ViewController A still exists), in which case we can now set its property, or it is nil (because ViewController A has gone out of existence), in which case we do nothing because that's what the question-mark means.

Upvotes: 1

Related Questions