0

Calling Bundle.main.loadNibNamed to load a .xib file which contains (n) multiple variants of one UI defined with multiple UIViews instantiates n instances of my subclass.

I then apply a filter expression to choose the correct variant with .first(where: { $0.restorationIdentifier == <correct restoration ID>.

In this instance my filter expression correctly returns the 5th UIView inside of my .xib but the @IBOutlets in my custom class are connected to the 1st UIView that was instantiated but which is immediately deprecated by what I assume is ARC.

This leads me to having unexpectedly nil IBOutlets. What can be done to connect the IBOutlets to the correct (5th in this case) UIView returned by Bundle.main.loadNibBaned

pinglock
  • 982
  • 2
  • 12
  • 30
  • That wasn't my assumption. To the best of my knowledge ARC handles object cleanup/deletion and so it was my assumption that ARC is killing off all the instances of my custom class that my filter expression drops. – pinglock Apr 02 '21 at 21:56
  • Oh yes, I misread the sentence. Yes, this makes sense, I'll delete my original comment. – Alexander Apr 02 '21 at 22:03

1 Answers1

1

The problem is that loadNibNamed is instantiating all your views, and you're only choosing to keep some of them around. In the process, IB outlets are assigned in some order, which most likely doesn't end up with your desired object being assigned to an outlet last.

I don't think a nib file gives you a way to instantiate only some of its multiple top level objects. You need to either split your various views into multiple nibs (and only load the one you need), or switch to using a Storyboard, which does let you instantiate specific objects by their identifier.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Thanks @Alexander. In that case, what are the benefits of multiple UViews within one .xib? From your answer it seems that the benefits are somewhat limited. – pinglock Apr 02 '21 at 21:57
  • Having multiple variants of a similar view in one "area" can be quite handy, for ensuring consistency, visualizing your app, and so on. Storyboards intentionally sought out to make this possible, where you can fish out and instantiate only specific view controllers, objects and such. – Alexander Apr 02 '21 at 22:05
  • Okay thanks. I must be misunderstanding the difference between .xibs and .storyboards. I thought xibs are for defining smaller UIViews within view controllers and storyboards are defining entire view controllers only. Best I can remember, last time I tried putting a free-form sized UIView within a storyboard, Xcode wouldn't allow it. – pinglock Apr 02 '21 at 22:16
  • @pinglock An "entire view controller" doesn't actually mean much. Often people make the mistake of thinking that a view controller should define an entire screen or something, but really, any view could have its own controller, even something as small as a button. – Alexander Apr 02 '21 at 22:36