【发布时间】:2012-07-17 18:22:11
【问题描述】:
在下面的代码中,xCode 的 Build & Analyze 函数检测到了一个
在第 165 行分配并存储到“addButton”中的对象的潜在泄漏。
addButton 是一个 UIBarButtonItem,它使用了 barItemWithImage 类别(我读到过 here),它返回一个自动释放的对象。如果我不保留 addButtonItem,我会在尝试访问已发布的对象时遇到异常。
我在这里错过了什么?
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;
分类代码:
@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];
}
@结束
【问题讨论】:
-
你说
[addButton retain],但据我所知,从不发布它。添加发布声明,看看是否可以修复它。我看到您正在释放toolbarItems,但添加它会增加其保留计数。
标签: objective-c memory-management memory-leaks