Why do I get a crash "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]" after setting rightBarButtonItem?
In my app, I have three buttons on the right hand side, one of which should alternate with the systemEditButton. So I set the buttons up withrightBarButtonItems (note the “s”) and then change the right-hand one using rightBarButtonItem when appropriate.
With 5.0, Apple lets you set multiple items in the leftBarButtonItems and rightBarButtonItems of a NavigationBar. It also says you can change the outer one with leftBarButtonItem and rightBarButtonItem respectively (“The first item in the array can also be set using the rightBarButtonItem property”).
Works fine the first time, but then it crashes when I put back the original button. Even worse, it doesn’t object when I set it, it crashes later during the animation of UINavigationBar layoutSubViews. Checking rightBarButtonItems after setting rightBarButtonItems shows it correctly updated the array, but it crashes during layout.
Well, I’ve confirmed this with a test program (see below), and submitted a bug-report to Apple. The workaround is to read the Items array and hand it back a new one with the zeroth element updated.