Tuesday, July 7, 2009

Gotta Love It

When my brain doesn't work, it doesn't work BIG. Here's the problem I've been having. I have inventory UITableViewCells that show information about a particular item. I wanted to reuse the cells in both the store and the player inventory (I know - how very C++ of me). Anyway, I used overkill to get it done with one cell. I had some trouble getting the item type images (wand, spellbook, etc.) to load on the fly in the cell, so I decided to just use the big ol' mallet and created several different UIImageView objects - one for each type. Then, when the cell was displayed, I was going to just remove the ones that weren't needed from the superview and it would all be happy. (For the un-Cocoa-initiated out there, I made several overlapping images and then hid the ones I didn't want seen). This worked fantastically the first time I tried it and I celebrated exuberantly. Until I scrolled down and scrolled back up. And my images were gone! WTH man?! I mean, c'mon - it JUST WORKED.
So I was trying to find some other less-desirable way of doing it. Not that the way I came up with was in any way, shape or form a good solution, but enough of that. So I was thinking - okay, maybe I can create a different cell for each type of item. But that means that I'll need that many different UITableViewCell classes. And my re-use of cells gets a little nasty. And then it dawned on me - re-use. Because we're using a simple object pool for the items displayed (a small collection of objects that are created when needed and stick around and are re-usable), each of my cells after the initial creation are going to be the same cells. What I had been doing was checking the type of the inventory item and then removing all of the OTHER images from the cell - but I wasn't putting back the one that was needed. So when I created a cell with a wand, say, it would show a wand. If that cell was then used for a spellbook, the wand image would get removed. And then if I needed the wand image back it wouldn't be available - it had been removed.
Eureka! So, now it's back to what I had before with a few minor modifications. I just hope that Xcode has a pretty substantial undo operation list... :) Overall, though, it is more than a little hacky at the moment and I need to clean it up and hopefully make it better before I release this puppy. And yes, that's a reminder to myself. ;)