Keep loop in Swift delegate

I have a UIViewController and in it a UIToolbar . They get a copy from the storyboard.

I created my own class for UIToolbar . Based on some logic, I make or don’t show buttons on it.

UIViewController needs to perform an action when some of the buttons are enabled. To do this, I created a delegate protocol in UIToolbar .

Currently, when I decline a view, it is stored in memory. Further research showed that my delegate created a conservation cycle.

In Objective-C, we simply define delegates as weak . However, I use Swift, and this does not allow me to define the delegate variable as weak :

 weak var navigationDelegate: MainToolBarDelegate? // 'weak' cannot be applied to non-class type 'MainToolBarDelegate' 

When I reject the view controller, I set self.toolBar.navigationDelegate = nil and the memory is cleared. But this is wrong!

Why am I getting a save loop and why can't I just define the delegate as weak ?

+8
ios swift delegates retain-cycle
source share
1 answer

weak references apply only to classes, not to structures or enumerations that are value types. But the default protocols can be applied to any of these types.

Define your MainToolBarDelegate as a protocol for classes only:

 protocol MainToolBarDelegate: class { } 

You can then declare your delegate as weak .

+14
source share

All Articles