Search code examples
iosmemorypropertiesnsdateretaincount

Is retainCount giving me the correct information for my NSDate?


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?


Solution

  • 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.