Let's say I have a property in my view controller, which is defined as follows:
@property (nonatomic, retain) UIImageView *checkmarkOffAccessoryView;
I @synthesize this in the implementation, release in -dealloc and initialize it in -viewDidLoad as follows:
self.checkmarkOffAccessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmarkOff.png"]] autorelease];
So far so good.
When I use it in my table view view as an auxiliary view for multiple cells, two things happen:
- Only one kind of cellular accessory shows an image
- The user interface of the application freezes.
The application does not crash because, as far as I can tell, the user interface simply stops responding. This is both in the simulator and on the device.
This is how I use the initialized property with my cell:
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { // initialize or dequeue cell... if (condition) cell.accessoryView = self.checkmarkOffAccessoryView; else cell.accessoryView = nil; }
Using the above code, only one cell shows the appearance of the accessory, and the user interface freezes.
If I initialize the UIImageView instance directly in the delegate method, I get all the UIImageView cells showing the appearance of the accessories, and I don't experience the user interface freezing:
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { // initialize or dequeue cell... if (condition) cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmarkOff.png"]] autorelease]; else cell.accessoryView = nil; }
My goal is to initialize as few objects as possible and reuse one UIImageView . I am curious why the first piece of code is problematic and what I can do to fix it.
It seems that the cell accessoryView property should just increment the retain self.checkmarkOffAccessoryView counter, but it seems like I'm missing some details.
What did I forget? Thank you for your advice.
EDIT
I think that:
self.checkmarkOffAccessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmarkOff.png"]] autorelease];
matches with:
UIImageView *uncheckedView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkmarkOff.png"]]; self.checkmarkOffAccessoryView = uncheckedView; [uncheckedView release];
In any case, I experience the same symptom of freezing.