4
NSLog(@"first:%u",[object retainCount]);
[object release];
NSLog(@"second:%u",[object retainCount]);

Output:

first:1
second:1

Why doesn't the object get released?

2

5 Answers 5

14

a Quote from NSObject reference on retainCount method

This method is typically of no value in debugging memory management issues. Because any number of framework objects may have retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number of deferred releases on an object, it is very unlikely that you can get useful information from this method.

3
  • 3
    BIG +1 for the docs quote. The main thing that method does is send developers to SO to ask increasingly insane questions.
    – Dan Ray
    Commented Mar 22, 2011 at 13:16
  • Haha, I love both these comments.
    – GoldenJoe
    Commented Mar 11, 2014 at 17:28
  • Except when you have objects that won't dealloc, and you can't run Instruments on them. SO is currently 99% noise, 1% signal on this topic thanks to all the "don't look at retainCount" responses
    – Adam
    Commented Mar 15, 2014 at 14:31
4

Object can be released but not when you think it will be. Basically, don't look at retainCount. It may not change until the next runloop or at all, it's an implementation detail. You will get a sense for when you need to release and when you don't with experience but until then rely on the clang analyzer.

1

First, retainCount doesn't give you a number you can use. It's meaningless.

Second, the reason the retainCount is 0 is probably that you try to work with an object that doesn't exist anymore. You're lucky your application doesn't crash, because your accessing invalid memory. Decreasing the retainCount just before deallocating an object is unnecessary, therefore Apple doesn't do it, probably.

1

Divide any number by zero and you will find the meaning of "object with retain count of zero".

-1

I agree with the other comments about not using retainCount to get a reliable count.

EDIT: Ignore my stupidity below... :)

However, I've observed that setting the corresponding property to nil...

self.object = nil;

the retainCount does tend to be decremented immediately.

3
  • and how is this supposed to answer the question? Commented May 17, 2013 at 0:05
  • Answer this and you'll understand the downvote; How is foo = nil; [foo retainCount]; any different from [nil retainCount]; or [0 retainCount];`?
    – bbum
    Commented May 17, 2013 at 14:41
  • Doh! I realised my mistake after posting that self.object = nil; would end up sending retainCount to a nil object, which obviously returns 0. Too slow with my edit to stop the downvote.
    – DarkMatter
    Commented May 18, 2013 at 16:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.