Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak reference in a closure

Tags:

closures

swift

I need to use a weak reference of self inside a closure. I am using the below code for this purpose:

func testFunction() { 
    self.apiClient.getProducts(onCompletion:  { [weak self] (error, searchResult) in     
        self?.isSearching = false
     }
}

Instead of giving the weak reference in the capture list of closure, can I declare a weak reference of self in the body of testFunction.

func testFunction() { 
     weak var weakSelf = self
     self.apiClient.getProducts(onCompletion: {(error, searchResult) in     
         weakSelf?.isSearching = false
     }
}

Similar, syntax was also used in Objective-C to use weak reference inside block.

__weak typeof(self) weakSelf = self; 

Is there any advantage of specify the weak reference through the Capture List in closure rather than declaring a weak variable in function body. If there are multiple closures in the function body, it makes more sense to declare a weak variable in function body and use the same variable in all the closures rather than writing as a capture list in each closure.

like image 500
Deep Arora Avatar asked Aug 15 '18 07:08

Deep Arora


1 Answers

These should behave identically. Which you use would be a matter of style. I wouldn't consider either approach particularly better.

It's worth noting that this use of weak may be unnecessary in either case. If getProducts is correctly written, this code should only create a temporary retain loop rather than a permanent one. After the completion handler is called, it should release the closure, releasing self and breaking the loop. So the question is whether it is reasonable and desirable to have self be destroyed go away before this completes, and so whether you really want weak here at all. I often use a strong pointer for these cases. (This is also a matter of style and opinion. There are arguments for the habitual use of weak, I just find it an unnecessary hassle in many cases.)

like image 148
Rob Napier Avatar answered Oct 27 '22 00:10

Rob Napier