2

When I create an object and check its retain count, I get 1 as expected. When I release the object and then check the retain count again, it is still 1. Shouldn't the object be deallocated, and the retain count 0?

NSMutableString *str=[[NSMutableString alloc] initWithString:@"hello"];
NSLog(@"reference count is %i",[str retainCount]);
[str release];
NSLog(@"reference count is %i",[str retainCount]);

I do see 0 for the retain count if I set str to nil first. Why is that?

jscs
  • 63,694
  • 13
  • 151
  • 195
devaditya
  • 321
  • 9
  • 21

2 Answers2

2

Do not depend on retainCount. And do not care about this. Lots of things may happen under the hood. You only need to ensure that you have released all the things that you owned. If you are trying to be sure that you are not leaking any memory, then use Instrument, not retainCount in NSLog.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • this answer was expected...well as it is written that after [obj release] reference count gets decremented...so it was just a practical implementation...not to check any LEAK...anyhow thanks... – devaditya Mar 05 '11 at 16:32
2

Don't use retainCount, it doesn't do what you expect in most cases.

Your second NSLog is accessing deallocated memory as an object. In this particular case, that deallocated memory still contains enough of the old data from the NSString that was just freed for the program to not crash when the retainCount method is called on it. Had you run this with NSZombieEnabled you would have gotten an error message about sending a message to a deallocated instance.

The reason it returns 0 when called for nil is that methods returning integers will always return 0 when called on a nil object.

Anomie
  • 92,546
  • 13
  • 126
  • 145
  • its much convincing...thanks...also program got crashed when i ran with programming tool with NSZombieEnabled enabled... – devaditya Mar 05 '11 at 16:36
  • to put it succinctly; messaging a deallocated object yields undefined behavior. End of story. – bbum Mar 05 '11 at 18:54