In the following code xCode’s Build & Analyze function detects a
Potential leak of an object allocated on line 165 and stored into ‘addButton’.
addButton is a UIBarButtonItem using the category barItemWithImage (which I read about here) which returns an autoreleased object. If I don’t retain addButtonItem I get an exception on trying to access a released object.
What am I missing here?
UIBarButtonItem *addButton;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
addButton = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"RedPlus.png"] target:self action:@selector(createStoryModal:)];
}else {
addButton = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"RedPlusiPhone.png"] target:self action:@selector(createStoryModal:)];
}
[addButton retain];
NSArray* toolbarItems = [NSArray arrayWithObjects:
addButton,
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil],
nil];
[toolbarItems makeObjectsPerformSelector:@selector(release)];
self.toolbarItems = toolbarItems;
The category code:
@implementation UIBarButtonItem(MyCategory)
+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:image forState:UIControlStateNormal];
[button setFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height)];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
return [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
}
@end
the static analyzer is right.
remove this:
and this:
and you’re also leaking a
UIBarButtonItem.NSArrayretains its elements.There may be other memory issues elsewhere, but that should remove three of the visible issues/bad forms.