View Full Version : Way of checking memory reference count?
Jan 4, 2006, 10:02 PM
For a while now I've been working on a piece of Cocoa software that I'm writing as part of my Master's thesis. I knew nothing about Cocoa before I started and I made some errors with memory leaks dealing with the copious amount off array insertion and deletion I do. Now I'm trying to fix those leaks, but it isn't the easiest thing to do as my code is pretty long and complicated and still not exactly an expert on reference count memory management.
My question is this: Is there any way to determine what the reference count is for a particular object, or rather part of memory? It would make my debugging a lot easier. I searched around online to try to find a way and I couldn't find one. It sure seems like it should exist....
Thanks in advance.
Jan 5, 2006, 03:25 AM
My question is this: Is there any way to determine what the reference count is for a particular object, or rather part of memory?
-(int)retainCount is a message that belongs to NSObject, so every object inherits it. It returns an int, which is how many times the object has been retained. Here is a simple example:
int count = [anyObject retainCount];
For the actual documentation: In XCode, click on the help menu, scroll down to documentation and select. In the far left column you will see Library. Click on Cocoa. Then go to the search field in the top right hand corner and type in the the method name: retaincount.
I made some errors with memory leaks dealing with the copious amount off array insertion and deletion...
Some things to remember about retain counts in terms of collections, i.e. NSMutableArrays and NSArray:
1. When you add/insert an object to a collection, the collection object sends a -retain message to the object.
2. When you remove an object from a collection object, the collection sends a -release message to the object.
3. When you release a collection object, the collection sends a release message to every object that resides in the collection.
Jan 5, 2006, 03:53 AM
In addition to Jordan72's comments, a reminder that if you obtain an object via either an alloc, copy or mutableCopy it has a retain count of one and should be released if you don't need to keep it. If you get an object any other way you can assume it is autoreleased and you don't need to release it. On the other hand if you need to keep it you should send your own retain message.
Jan 5, 2006, 11:29 AM
Thanks guys. That should help me a lot. In the beginning I didn't realize the whole adding and removing an object increments and decrements the reference count. So I got myself into trouble.