Currently I am creating custom table view cells for iPhone using [[NSBundle mainBundle] loadNibNamed:owner:option:] to load the nib. When I profile my app, a memory leak is produced every time I open the view using these custom table cells. The leaks instruments points me to the [[NSBundle mainBundle] loadNibNamed:owner:option:] line. Here is my code:
static NSString *challengeCellIdentifier = @"challengeListTableCell";
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
ChallengeListTableCell *cell = (ChallengeListTableCell *) [tableView dequeueReusableCellWithIdentifier:challengeCellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"ChallengeListTableCell"
开发者_如何学JAVA owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if([currentObject isKindOfClass:[ChallengeListTableCell class]]){
cell = (ChallengeListTableCell *) currentObject;
break;
}
}
}
// Configure the cell...
if(indexPath.row == 0){ // top
[cell.backgroundImg setImage:[UIImage imageNamed:@"topMenuBar.png"]];
[cell.selectedBackgroundImg setImage:[UIImage imageNamed:@"topMenuBarOn.png"]];
}else if(indexPath.row == [challenges count]-1){ //bottom
[cell.backgroundImg setImage:[UIImage imageNamed:@"bottomMenuBar.png"]];
[cell.selectedBackgroundImg setImage:[UIImage imageNamed:@"bottomMenuBarOn.png"]];
}else{ //middle
[cell.backgroundImg setImage:[UIImage imageNamed:@"middleMenuBar.png"]];
[cell.selectedBackgroundImg setImage:[UIImage imageNamed:@"middleMenuBarOn.png"]];
}
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { //ipad
[cell.title setFont:[UIFont fontWithName:@"MuseoSans-500" size:40.0f]];
}else{ //iphone
[cell.title setFont:[UIFont fontWithName:@"MuseoSans-500" size:20.0f]];
}
Challenge * challenge = [challenges objectAtIndex:indexPath.row];
[cell.title setText:challenge.title];
if([challenge.completed boolValue]){
[cell.checkImage setImage: [UIImage imageNamed:@"checkComplete.png"]];
} else {
[cell.checkImage setImage: [UIImage imageNamed:@"checkNotComplete.png"]];
}
return cell;
Documentation states that the array returned from loadNibNamed:owner:options: is an autoreleased object, so I don't understand why this causes a leak. Has anyone else had this problem?
You aren't releasing the autorelease pool you alloc.
Looks like poor design...
If the table view cannot recycle a cell, you are loading a NIB... This is wrong, because the NIB may be loaded, even if the cell can't be recycled.
Then, you assume your for
loop will get a valid instance. No error checking. Bad...
Finally, you allocate an autorelease pool (don't know why in such a case). You just forgot to release it.
精彩评论