112

I would like to know in what situation did you use -retainCount so far, and eventually the problems that can happen using it.

Thanks.

Lorenzo B
  • 33,006
  • 23
  • 110
  • 185
Moszi
  • 3,208
  • 2
  • 20
  • 20
  • 5
    you should **never** user the `-retainCount`. – holex May 04 '13 at 10:24
  • 3
    (Except when you should. It is *very occasionally* useful to help understand what's going on, so long as you appreciate that it can be seriously misleading at times. And, of course, it's not allowed at all if using ARC.) – Hot Licks Jun 02 '13 at 12:13

11 Answers11

245

You should never use -retainCount, because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.

For example:

  • You'd think that [NSNumber numberWithInt:1] would have a retainCount of 1. It doesn't. It's 2.
  • You'd think that @"Foo" would have a retainCount of 1. It doesn't. It's 1152921504606846975.
  • You'd think that [NSString stringWithString:@"Foo"] would have a retainCount of 1. It doesn't. Again, it's 1152921504606846975.

Basically, since anything can retain an object (and therefore alter its retainCount), and since you don't have the source to most of the code that runs an application, an object's retainCount is meaningless.

If you're trying to track down why an object isn't getting deallocated, use the Leaks tool in Instruments. If you're trying to track down why an object was deallocated too soon, use the Zombies tool in Instruments.

But don't use -retainCount. It's a truly worthless method.

edit

Please everyone go to http://bugreport.apple.com and request that -retainCount be deprecated. The more people that ask for it, the better.

edit #2

As an update,[NSNumber numberWithInt:1] now has a retainCount of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.

Dave DeLong
  • 239,073
  • 58
  • 443
  • 495
  • 4
    Thanks @Dave-Delong for your examples. – Moszi Jan 11 '11 at 00:01
  • 1
    retainCount is currently useful for singletons.(Now the question is how useful are singletons...) `- (NSUInteger)retainCount{return NSUIntegerMax;}`. – Joe Mar 22 '11 at 13:05
  • 8
    @Joe you can make a singleton without overriding `retainCount`. – Dave DeLong Mar 22 '11 at 14:12
  • 1
    One can also bake a cake without eggs. Apple recommends overriding the retainCount to ensure the status of the of the singleton in a non-garbage collecting environment. http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32 – Joe Mar 22 '11 at 14:18
  • 5
    @Joe I'm aware of that; Google "objective-c singleton" for all the discussion on why that example isn't a very good one. – Dave DeLong Mar 22 '11 at 16:42
  • 2
    One thing that I use--@DaveDeLong, you might find this wrong too, but I don't think so--is to overwrite the deallocs and the inits and put NSLogs in them (even with ARC). This gives me a great idea of whether objects are getting dealloced or not, which is the real question we're usually trying to answer.. – Dan Rosenstark Aug 12 '12 at 03:14
  • @Yar - this can be somewhat useful in ARC, because the `dealloc` methods can still be used, just for clean-up rather than memory management. In the rare cases I need to do this I tend to breakpoint rather than log. – lxt Aug 15 '12 at 11:42
51

NEVER!

Seriously. Just don't do it.

Just follow the Memory Management Guidelines and only release what you alloc, new or copy (or anything you called retain upon originally).

@bbum said it best here on SO, and in even more detail on his blog.

Community
  • 1
  • 1
Abizern
  • 129,329
  • 36
  • 198
  • 252
  • 8
    Because you'll think you're counting memory, but you will be doing it wrong. – Abizern Jan 08 '11 at 21:12
  • @Abizern - and what about the singleton situation in one of the other answers ? – Moszi Jan 08 '11 at 21:15
  • The point of a singleton is that there is only one instance of the object, not that it is never dealloced. If you follow the memory management rules when creating a singleton object, it won't be deallocated until every object that has retained it has released it, which is as it should be. – Abizern Jan 08 '11 at 21:20
  • 3
    To add to this, any information you could gain from `-retainCount` can be gotten (with much more detail) from Instruments and its tools. – Dave DeLong Jan 08 '11 at 21:45
  • 3
    To add to what Dave said; the absolute retain count of an object is an implementation detail. Both a detail of the internals of the object and/or a detail of any other object the object may have been passed through. Calling `retain`, `retain`, `retain`, `autorelease, `autorelease, `autorelease` could be a perfectly valid result of passing an object through the UIKit API, for example. – bbum Jan 09 '11 at 00:25
  • You'll know `retainCount = 0` when your application crashes ;) *(Sarcasm intended)* – d11wtq Jan 09 '11 at 00:51
  • 2
    @d11wtq If retainCount ever == 0, the singularity has been achieved! – bbum Jan 09 '11 at 18:41
14

Autoreleased objects are one case where checking -retainCount is uninformative and potentially misleading. The retain count tells you nothing about how many times -autorelease has been called on an object and therefore how many time it will be released when the current autorelease pool drains.

Jonah
  • 17,609
  • 1
  • 41
  • 68
  • 1
    Thanks - this is a good point. This is the first answer which actually has a reason described why not use retainCount, besides the generic "don't". – Moszi Jan 08 '11 at 21:30
  • 1
    @Moszi: Your question was "When to use retainCount?" — if you didn't mean to ask that question, you should have asked something else. – Chuck Jan 08 '11 at 22:06
  • @chuck - actually i was interested in "when to use it", however it seems that every answer is going to be "never" ... But - I guess you are right. I will leave the question open for a couple of days, and if there is going to be no answer other then never, then i will accept "never" as an answer. – Moszi Jan 08 '11 at 23:39
10

I do find retainCounts very useful when checked using 'Instruments'.

Using the 'allocations' tool, make sure 'Record reference counts' is turned on and you can go into any object and see its retainCount history.

By pairing allocs and releases you can get a good picture of what is going on and often solve those difficult cases where something is not being released.

This has never let me down - including finding bugs in early beta releases of iOS.

Egil
  • 3,967
  • 4
  • 18
  • 13
5

Take a look at the Apple documentation on NSObject, it pretty much covers your question: NSObject retainCount

In short, retainCount is probably useless to you unless you've implemented your own reference counting system (and I can almost guarantee you won't have).

In Apple's own words, retainCount is "typically of no value in debugging memory management issues".

NANNAV
  • 4,718
  • 4
  • 26
  • 48
lxt
  • 30,690
  • 5
  • 76
  • 83
  • First of all thank you for you answer. Usually peoples reaction to this question is "NEVER". (See the answers). Actually "no value in debugging" doesn't mean "NEVER". So my question is – why is the strong feeling of not using it (for instance in singleton implementation - one of the answers again) ? – Moszi Jan 08 '11 at 21:13
  • I guess you would need to provide more information about what you're using it for. An acceptable use would be, as suggested by Apple, overriding retainCount to implement your own reference counting system. But in practice, you'd never see that (I never have, anyway). The strong reaction generally comes from the fact Apple themselves have advocated (in their mail groups, the docs, the dev forums, etc) to leave retainCount alone. – lxt Jan 08 '11 at 21:21
  • 1
    @Moszi: Debugging is the only situation in which most people could conceive of it having value, so if it is unreliable there, it is never useful. What other uses are you thinking of? – Chuck Jan 08 '11 at 21:45
4

Of course you should never use the retainCount method in your code, since the meaning of its value depends on how many autoreleases have been applied to the object and that is something you cannot predict. However it is very useful for debugging -- especially when you are hunting down memory leaks in code that calls methods of Appkit objects outside of the main event loop -- and it should not be deprecated.

In your effort to make your point you seriously overstated the inscrutable nature of the value. It is true that it is not always a reference count. There are some special values that are used for flags, for example to indicate that an object should never be deallocated. A number like 1152921504606846975 looks very mysterious until you write it in hex and get 0xfffffffffffffff. And 9223372036854775807 is 0x7fffffffffffffff in hex. And it really is not so surprising that someone would choose to use values like these as flags, given that it would take almost 3000 years to get a retainCount as high as the larger number, assuming you incremented the retainCount 100,000,000 times per second.

Marc Culler
  • 141
  • 2
3

What problems can you get from using it? All it does is return the retain count of the object. I have never called it and can't think of any reason that I would. I have overridden it in singletons to make sure they aren't deallocated though.

ughoavgfhw
  • 39,083
  • 6
  • 98
  • 121
  • 2
    There is no reason to override it in the singleton case. There are no code paths in the Foundation/CoreFoundation that use `retainCount` for memory management. – bbum Jan 09 '11 at 00:23
  • Doesn't release use it to decide if it should call dealloc? – ughoavgfhw Jan 09 '11 at 02:35
  • 2
    Nope; the internal implementation of retain/release/autorelease has deep roots in CoreFoundation and is really not at all what you might expect. Go grab the CoreFoundation source (it is available) and have a look. – bbum Jan 09 '11 at 18:42
3

You should not be worrying about memory leaking until your app is up and running and doing something useful.

Once it is, fire up Instruments and use the app and see if memory leaks really happen. In most cases you created an object yourself (thus you own it) and forgot to release it after you were done.

Don't try and optimize your code as you are writing it, your guesses as to what may leak memory or take too long are often wrong when you actually use the app normally.

Do try and write correct code e.g. if you create an object using alloc and such, then make sure you release it properly.

ExitToShell
  • 460
  • 4
  • 14
0

You should never use it in your code, but it could definitely help when debugging

iosdevnyc
  • 1,845
  • 5
  • 25
  • 46
0

Never use the -retainCount in your code. However if you use, you will never see it returns zero. Think about why. :-)

hrchen
  • 1,203
  • 13
  • 17
0

The examples used in Dave's post are NSNumber and NSStrings...so, if you use some other classes, such as UIViews, I'm sure you will get the correct answer(The retain count depends on the implementation, and it's predictable).

Peng
  • 1
  • 3