Search code examples
swiftmacosretain-cycleiboutletcollection

Swift IBOutlet collections and retain cycle safety


I’ve been trying to use Swift outlet collections in a MacOS project for some time, and have only just learned this isn’t currently possible. I’m still puzzled why not, but presuming this is amended at some point, I have another concern.

I understand that outlets should generally be weak, except for the “root” outlet, to prevent retain cycles:

@IBOutlet weak var someButton: NSButton!

But the examples I’ve found for collection syntax don’t include the weak modifier, and I haven’t found a place to put it that (1) makes sense, and (2) doesn’t get a red flag:

@IBOutlet var severalButtons: [NSButton]!

So, am I missing something obvious? Could I be sure such an outlet collection wouldn’t create a retain cycle? (Presuming they’re ever allowed?)


Solution

  • An IBOutletCollection, unlike an IBAction or an IBOutlet, takes a class name as an argument. As a top-level object, an IBOutletCollection should be declared strong. This is explained in more detail here.

    Therefore, due to this restriction, an IBOutletCollection has the potential to create a retain cycle.