0

I have NSDate property

In .h

...
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
...
      NSDate *pageStartDate;
...
}
...
@property (nonatomic, retain) NSDate *pageStartDate;
...

In .m

...
-(void)myMethod
{
   ...
   // set date of start showing page
   NSDate *tempStartDate = [NSDate date];
   [tempStartDate retain];
   pageStartDate = tempStartDate;
   [tempStartDate release];
   ...
}
...

After running this code the [tempStartDate retainCount] = 1 - is it normal? If I write self.pageStartDate = tempStartDate than [pageStartDate retainCount] = 2.

Is there right use of NSDate, or not is?

Abizern
  • 146,289
  • 39
  • 203
  • 257
Sound Blaster
  • 4,778
  • 1
  • 24
  • 32

2 Answers2

1

If you don't write self.pageStartDate it won't use the property, so yes, the retain count of 1 is expected. Also, note that this instance is autoreleased (because you created it with [NSDate date]), so it will be released later.

If you were using the property, you wouldn't need the retain and release statements.

André Morujão
  • 6,963
  • 6
  • 31
  • 41
0

The problem isn't just your NSDate its because you've used retainCount

Annotation:

NSDate *tempStartDate = [NSDate date]; // No alloc, retain, copy, or mutableCopy - so assume autoreleased instance
[tempStartDate retain]; // You call retain - you own this now
pageStartDate = tempStartDate; // Not going through the setter. :(
[tempStartDate release];  // You've released this correctly, except for the step above.
                          // pageStartDate is now pointing to a garbage pointer.

You've done the right thing by releasing what you've retained, but pageStartDate didn't hold on to the value.

Try this

self.pageStartDate = [NSDate date];

Since you are using retain for the pageStartDate property, this will retain the value for you.

But - trying to use retainCount to check your memory management is, basically, doing it wrong.

Community
  • 1
  • 1
Abizern
  • 146,289
  • 39
  • 203
  • 257
  • In which case accepting my answer and/or upvoting is the usual way of thanking someone on SO. – Abizern Jun 02 '11 at 12:39
  • But I think about this: `self.pageStartDate = [NSDate date]; NSLog(@"[pageStartDate retainCount] = %i", [pageStartDate retainCount]);` In Log I see `[pageStartDate retainCount] = 2` - is it normal? Because I have ONE `release` of `pageStarDate` in my code - in `-(void)dealloc` – Sound Blaster Jun 02 '11 at 12:39
  • 1
    DON'T USE `retainCount`. It tells you nothing about running code. See the link in my answer. Just worry about the memory management rules and don't look at what `retainCount` tells you. Remember - the date value is `autoreleased` - which means it will be released when the autorelease pool drains which may no be immediately. – Abizern Jun 02 '11 at 12:42
  • Oups, I didn't catch link in your answer. Thank again! – Sound Blaster Jun 02 '11 at 12:47