Dvole Dvole - 1 year ago 108
iOS Question

Is IBOutletCollection guaranteed to be of correct order?

I have two contradicting sources in regards to IBOutletCollection with NSArray.
First says that the order that you link things from interface to outlet collection is significant, and it will always be the same in outlet collection. E.g. if we link first text field first to collection, element number 0 will be that field, etc.

But another source tells me that this is wrong and actually Outlet collection is randomized and there is absolutely no guarantee in the order of things. So element number zero can be any text field, and not just the first connected in interface.

"iOS 6 Programming - exploring iOS SDK" is the first source and Stanford course on iTunes is the second source.
Who is right?

Answer Source

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.