【问题标题】:Incorrect decrement of the reference count of an object对象引用计数的不正确递减
【发布时间】:2011-09-10 12:45:44
【问题描述】:

我不知道如何处理释放这个对象:

h:

@interface AHImageView : UIScrollView
{
UIImageView *imageView;
}
@property (nonatomic, retain) UIImageView *imageView;

.m:

-(id)initWithFrame:(CGRect)frame {
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

 [self addSubview:self.imageView];
}

-(void)dealloc {
    [super dealloc];
    self.imageView = nil;
    [self.imageView release];
}

我得到的错误是:

不正确的对象的引用计数递减不正确 此时由调用者拥有

这个错误指向[self.imageView release]; 行。

【问题讨论】:

  • 那行完全没有必要

标签: iphone objective-c memory-management


【解决方案1】:

您在nil 上致电发布。要么删除 self.imageView=nil;(释放 imageView 并将其设置为 nil)或 [imageView release];(仅释放 imageView,但您不会进一步使用它,因此没有理由将其设置为 nil)。

编辑: 正如@Bavarious 所说,这里有泄漏:

self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];

你应该这样称呼它:

self.imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)] autorelease];

【讨论】:

  • 请注意,他正在泄漏 self.imageView-initWithFrame: 返回一个已分配给 retain 属性的拥有对象。
  • 要添加到您的答案中,必须在 dealloc 方法中将其设置为 nil...self.imageView = nil;
  • 如果你在发布后设置为 nil ,那么它就可以了。但你不能在发布之前将它设置为 nil...
  • 暂时忘记其他一切,[self.imageView release]; 本身会导致引用计数的错误减少,因为它是calling release on the object returned by the accessor。应该是[imageView release]
  • 所以我应该自动释放保留属性的任何内容?例如,我还有一个保留的 nsmutablearray 需要释放,但是当我将发布代码放入 dealloc 时会给出相同的错误。
【解决方案2】:

你的 dealloc 方法有两个错误:

(1) 你应该把[super dealloc] 作为你的dealloc中的最后

如果你首先调用[super dealloc],你的对象所在的内存将被释放(并且可能被其他东西使用)。在那之后,你不能使用你的对象的成员,它们不再是你的了!

(2) 最好不要在你的 dealloc 方法中使用属性。你不知道这还会导致什么发生(其他对象可能正在通过 KVO 监听,子类可能已经覆盖了 setter 以执行其他操作等)。

你正确的dealloc应该是这样的:

- (void)dealloc {
    [imageView release];
    [super dealloc];
}

希望有帮助!

【讨论】:

【解决方案3】:

为了避免释放和泄漏问题,像这样修改dealloc方法的代码。

-(void)dealloc
{    
    [imageView release];
    self.imageView = nil;
    [super dealloc];
}

问题解决了。

【讨论】:

猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 2011-05-05
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多