Is IBOutletCollection guaranteed to be of correct order?

It seems like in Xcode 7.x IBOutlet collection is ordered.

For sure, you can assign tag property to every element in collection in needed order and do something like

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.outletCollection = [self.outletCollection sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"tag" ascending:YES]]];
}

Both sources are sort of right: on one hand, due to the implementation details of the Interface Builder, the order in which you add items to IBOutletCollection will be maintained on retrieval; on the other hand, you should avoid making use of that ordering in your code, because there is no way to check this order.

Imagine taking over someone else's project. If you see a loop over an IBOutletCollection, observe that the order of iteration matters, and decide to check what that order is or force the new order, you would have to remove and re-add the controls to your outlet collection. That is why you should treat your IBOutletCollection elements as unordered. If it is necessary to maintain a specific order, copy the elements into an NSArray, sort them on some known property, and then iterate the copied collection.


Simply assign the order of controls by tag and on load reorder them.


property observing:

@IBOutlet var btnCollection: [UIButton]! {
    didSet {
        btnCollection.sort { $0.tag < $1.tag }
    }
}

in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    btnCollection = btnCollection.sorted { $0.tag < $1.tag }
}

Tags:

Ios

Ios6