Why does ivar for UITableViewCell accessory view go bad?


I have a working solution for the Silver Challenge but one thing is driving me nuts. To indicate which rows have been marked as Favorites, I am setting the accessoryView of the UITableViewCell as such:

if ([[BNRFeedStore sharedStore] itemIsFavorite:item]) { UIImageView *favoriteImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"heart"]]; [cell setAccessoryView:favoriteImageView]; } else { [cell setAccessoryView:nil]; }

Looks good! Though it bugs me that I’m creating a new UIImageView (and I suspect reloading the image) each time. I tried declaring UIImageView *favoriteImageView as an instance variable, defining it by instantiating the UIImageView once in initWithStyle; such that the code above then looks like this:

if ([[BNRFeedStore sharedStore] itemIsFavorite:item]) { [cell setAccessoryView:[self favoriteImageView]]; } else ...

when I do this, the first entry that I favorite works fine, the second one I favorite hangs up the app; when I try to re-load the app when there is more than one favorite entry, the app never loads past a blank black screen. Must a view for a table cell’s accessoryView only be used by a single cell, or am I doing something wrong?


Yes, a view instance can only appear on the screen once. Thus, you will need a separate view instance for each cell.