0

If a retain (reference) count of an object is greater than 1 in a dealloc method right before releasing does this mean there will be a memory leak?

I was debugging my code to find another issue but then ran into this subtle one. One of my object's retain counts was 3 in the dealloc method. This object is a property with retain and is only called within the class. Now I imagine that the retain count should be 1 for all objects in the dealloc method before releasing right?

Here's a sample dealloc method in a custom class:

- (void)dealloc {
    // Prints: "myObject retaincount: 3"
    NSLog(@"myObject retaincount: %d", [myObject retainCount]);

    // myObject retain count will be 2 after this call
    [myObject release];

    [super dealloc];
}

Is this normal?

4

3 回答 3

6

来自 Apple 关于-retainCount

重要提示:此方法在调试内存管理问题时通常没有价值。因为任何数量的框架对象可能已经保留了一个对象以保存对它的引用,而同时自动释放池可能在一个对象上保存了任何数量的延迟释放,所以您不太可能从中获得有用的信息方法。

于 2010-06-23T22:58:48.337 回答
2

如果myObject通过方法(例如“方法:”)传递给其他对象(例如“anObj”),如

 [anObj method:myObject];

anObjmyObject如果需要可以保留。那么dealloc在调用包含的对象时myObject,其保留计数myObject大于1是完全合理的。

您的代码仍然可以:包含对象的责任是在release完成后拥有所有权。之后[myObject release]myObject将不会被释放。相反,它会在释放时被anObj释放。

于 2010-06-23T16:26:20.317 回答
0

What you want to do instead of printing out the retain count, is to run the ObjectAlloc Instrument against your code, with reference counting turned on (click on the (i) of the instrument and re-start the instrument recording your app).

Then you can go to a specific instance of an object, and get the full retain/release history for it - that can help figure out if something is retaining the object that should not be.

Another quick check would be to set a breakpoint or put a log in dealloc of whatever class myObject is, so that you can see directly if the object is getting deallocated when you expect it to - it could be that it's still got a larger retain count there, but once the autorelease pool is emptied it will go away.

于 2010-06-24T04:56:18.640 回答