触摸后UIButton保持反向增加

时间:2011-06-14 17:14:10

标签: objective-c ios memory-management memory-leaks retaincount

我创建了一组相同的自定义类型的对象。所有对象的方法showDeleteButton都有hideDeleteButton。 我发现当我隐藏删除按钮(删除它)时按下的按钮有retainCounter == 2.

这里是代码:

-(void)showDeleteButton {
if(!isDeleteButtonLoaded) { // Check that method was't triggered twice
    UIButton *aDeleteButton = [[UIButton alloc] initWithFrame:CGRectMake(-3, -7, 30, 29)]; // RC == 1
    [aDeleteButton setImage:[UIImage imageNamed:@"close_button.png"] forState:UIControlStateNormal];
    [self addSubview:aDeleteButton]; // RC == 2
    [aDeleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    deleteButton = aDeleteButton;
    [aDeleteButton release]; // RC == 1
    isDeleteButtonLoaded = YES;
    NSLog(@"delete button retain count (created): %d", [deleteButton retainCount]);
    [self setNeedsDisplay];
}

}

-(void)deleteButtonPressed:(id)sender {
[delegate deleteImageAtPath:self.imageFullPath];

}

-(void)hideDeleteButton {
if(isDeleteButtonLoaded) {
    NSLog(@"delete button retain count (before): %d", [deleteButton retainCount]); // RC == 1
    [deleteButton removeFromSuperview]; // RC == 0
    deleteButton = nil;
    isDeleteButtonLoaded = NO;
    [self setNeedsDisplay];
}

}

因此对于按下按钮NSLog的第二种方法显示RC == 2!有任何想法吗?我100%确定无法从类外部访问deleteButton。

4 个答案:

答案 0 :(得分:5)

请勿查看保留

就任何理智的人而言,

retainCount毫无意义,只要你遵守记忆规则,事情就会好起来。

答案 1 :(得分:0)

永远不要查看retainCounts以获取任何有用的信息。在Apple的内部框架中,他们可以随时调用保留或释放您的对象。您需要担心的是您的retain(或alloc,或copy)和release语句是否正确匹配。将视图添加为另一个视图的子视图(或将其添加到任何NSArray)也会增加其retainCount ...但您不必担心这一点。

答案 2 :(得分:0)

请参阅stackoverflow popular question,了解为什么从不使用retainCount而是使用Apple工具来跟踪内存泄漏。

答案 3 :(得分:0)

不要使用retainCount。结果充其量是误导。

首先是商家,请阅读Apple's memory management guidelines

其次,使用这些指南来修复代码中的一些内存问题:

UIButton *aDeleteButton = [[UIButton alloc] initWithFrame:CGRectMake(-3, -7, 30, 29)];
// Retain count +1
// Some code...
deleteButton = aDeleteButton;
[aDeleteButton release];
// Retain count -1

您分配了一个新的UIButton然后将其释放。这意味着该按钮不归您所有,并且可能随时消失。我猜你班上有一个名为deleteButton的财产?如果是这样,请按照以下方式使用它:self.deleteButton = aDeleteButton;

hideDeleteButton方法中,您可能希望使用如下所示的内容:

[self.deleteButton removeFromSuperview];
self.deleteButton = nil;
isDeleteButtonLoaded = NO;
[self setNeedsDisplay];

同样,这假设您的类中有一个名为deleteButton的属性。如果您没有,请制作一个并使用它。它极大地简化了内存管理任务。