Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

DaveP

macrumors 6502a
Original poster
Mar 18, 2005
506
433
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.
 

Jordan72

macrumors member
Nov 23, 2005
88
0
DaveP said:
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.

DaveP said:
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.
 

caveman_uk

Guest
Feb 17, 2003
2,390
1
Hitchin, Herts, UK
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.
 

DaveP

macrumors 6502a
Original poster
Mar 18, 2005
506
433
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.