在以下代码中,xCode 的 Build & Analyze 函数检测到
在第 165 行分配并存储到“addButton”中的对象的潜在泄漏。
addButton 是一个 UIBarButtonItem 使用类别 barItemWithImage (我在这里读到),它返回一个自动释放的对象。如果我不保留 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];
}
@结尾