Todays Surprise using NSMutableArray
I am programming in Objective-C for 4+ years now. And don’t get me counting, how many years have passed, since I programmed my first program in school. After that amount of time, surprises in programming are not that common any more for me. After so many years, you develop a gut feeling, what is safe programming and what is possibly not a good idea.
Today, I was reminded again, that it is a good idea to listen to your gut feeling. I was combining a loop through a collection of items together with an act of deleting one of the items. When I was programming it, my gut feeling told me, wait – this could be confusing for the array management (class) software. May be, it has a reference to an item and I am deleting it and this confuses everything.
So I checked the description of the class. I could not find any comments regarding that and went on.
A few days later however, after I had programmed it, I learned, that I had not looked up the documentation good enough. Somewhere in the documentation I found the hint: Deleting an element while enumerating it (running in a loop through all elements of that array) is potentially unsafe. The same applies to adding elements or replacing elements. So I needed to change my implementation.
I didn’t know what to feel. Should I be proud, because I had “felt it”? Should I feel stupid, programming it that way? Should I be upset, because it sure is possible (for Apple) to implement the array thing without these problems. But when programming, you have to make tradeoffs. This way, the more general case is surely faster.
So how did I do it? I changed my code to first collect all elements, that need to be deleted, in a second array and then, after the enumeration loop has finished, delete them all at once.
The alternative implementation is a good idea as well: Make a copy of the collection, enumerate through the copy and modify the original.