0

Here I got some ugly code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
NSDate *date = [NSDate date];
NSString *textWithYear = [NSString stringWithFormat:@"text and year %@", [dateFormatter stringFromDate:date] ];
[dateFormatter release];
NSLog(@"%i", [dateFormatter retainCount]); // returns 1 !

As you see, retains counter returns 1, which I suppose means that the object is not released. If I change that string to

[dateFormatter release], dateFromatter = nil;

retains counter returns 0, which is supposedly because it can't count retains for nil :)

Is there something that I don't understand about retains counter, or this object is really not released? When I send release to it for the second time (striving to get zero retains count) it crushes expectedly :)

And one more question: if the dateFormatter was really released, why doesn't it crash when i call [dateFormatter retainCount] ?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
nikans
  • 2,468
  • 1
  • 28
  • 35

1 Answers1

7

You are correctly releasing your object; don't worry about the retain count. And don't use -retainCount. See When to use -retainCount? or Calling -retainCount Considered Harmful for more details about why.

Do note that your code here will crash if the object does get destroyed (because the call to -retainCount comes after you've released it and may be to a dangling pointer); setting your variables to nil after you are done with them is a good habit to protect against this. But it has nothing to do with whether your code is leaking.

Community
  • 1
  • 1
Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60
  • One question: if the `dateFormatter` was really released, why doesn't it crash when i call [dateFormatter retainCount] ?.. – nikans Sep 08 '11 at 21:47
  • @Seamus you mean "if the object does get deallocated", right? There could be other references keeping it alive. – Richard Sep 09 '11 at 00:40
  • @Richard - yes; in fact, other references are clearly keeping this object alive. Edited, thanks. – Seamus Campbell Sep 09 '11 at 00:57
  • 2
    Or it could be coincidence. Freeing memory doesn't change the contents and, thus, a dangling pointer will appear to continue to work until something does scribble on the memory. – bbum Sep 09 '11 at 01:40
  • 1
    (Which is why you can't rely on `retainCount` to tell you *anything*.) – Peter Hosey Sep 09 '11 at 04:12