Why fatal nil error when assigning new control to a class member, but succeeds when assigning to a local variable?

I have a subclass of UIToolbar with a member variable for one of the controls that will display on the toolbar. After creating the toolbar, I call a method that adds the control to the toolbar. When I create the control and assign it to the member variable, I get a fatal nil error. However, when i create it and assign it to a local variable it succeeds. While I have it working with a local variable, I'd like to understand the reason this adjustment works. Any insights would be much appreciated.

categoryCtl = VGSegment(frame: placeholder.frame, segmentConfiguration: config, titles: titles)
       
categoryCtl.delegate = delegate
       
let tbButton = UIBarButtonItem(customView: categoryCtl)

Above fails at line 3 with fatail nil error. However, if i change it as follows, it succeeds.

let segment  = VGSegment(frame: placeholder.frame, segmentConfiguration: config, titles: titles)
       
segment.delegate = delegate
       
categoryCtl = segment
       
let tbButton = UIBarButtonItem(customView: segment)

Line 3 succeeds and program works as expected.

You have access to the debugger, and if you don't want to use the debugger you can use "print" statements to at least find out whether "categoryCtl" or "delegate" is nil in the first line 3. ("delegate" == nil could crash with this error if it's declared as type "WhateverDelegate!".)


At a wild guess, I'd suggest you have a memory management error where "categoryCtl" is not being kept alive properly, and more or less by accident the second code fragment creates a retain cycle that keeps it alive.


One other point to look at: Make sure you know what types each of the variables is, in particular whether it is optional, non-optional or an implicitly unwrapped optional. Sometimes, inexplicable behavior starts to make sense when you find that something is optional that shouldn't be.

The debugger shows that segmentCtl is nil when assiging the delegate. The code is a keyboard extension. I think that may be influencing the issue. It may be related to the object being created off the main thread. Not really sure though. I oughta take a look at that.

Why fatal nil error when assigning new control to a class member, but succeeds when assigning to a local variable?
 
 
Q