I have an application where I initially set a UIButton’s background image, and then need to change it to something else later. I do realize I could just remove the original button and allocate a new button with the new image, but I’d prefer to be more efficient and reuse the object that I’ve already allocated. Is is possible to do this? I noticed that the currentBackgroundImage property is readonly, so when I try stuff like:
[thumbnailButton setBackgroundImage:nil forState:UIControlStateNormal];
[thumbnailButton setBackgroundImage:[UIImage imageWithCGImage:[[photos objectAtIndex: currentPhotoIndex] thumbnail]] forState:UIControlStateNormal];
or just:
[thumbnailButton setBackgroundImage:[UIImage imageWithCGImage:[[photos objectAtIndex: currentPhotoIndex] thumbnail]] forState:UIControlStateNormal];
I get the following:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellContentView setBackgroundImage:forState:]: unrecognized selector sent to instance 0x16c570'
Is it possible to accomplish using UIButton or do I just need delete the original button and create a new one?
You have a memory management problem here.
This means that your
thumbnailButtonis not pointing at aUIButton, but rather aUITableViewCellContentView. This could happen by improper assignment or if the UIButton is deallocated (in this case you have have a dangling pointer). Run the analyzer and double check your use of the button.UIButton buttonWithTypereturns an autoreleased instance, so you need to retain it.