开发者

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 runn开发者_如何学Pythoning 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜