我希望确保我正确理解了内存管理。在这里使用其中一种assignCurrentDate方法是否有特殊原因?此外,所有这些方法都不会导致内存泄漏,对吗?
在.h文件中,我们有:
NSDate *currentDate1;
NSDate *currentDate2;
NSDate *currentDate3;
NSDate *currentDate3;
//and
@property (nonatomic, retain) NSDate *currentDate1;
@property (nonatomic, retain) NSDate *currentDate2;
@property (nonatomic, retain) NSDate *currentDate3;
@property (nonatomic, retain) NSDate *currentDate4;
在 .m 文件中:
-(void) assignCurrentDate1
{
currentDate1 = [[NSDate date]retain];
//[NSDate date] is autoreleased
}
-(void) assignCurrentDate2
{
currentDate2 = [[NSDate date]copy];
}
-(void) assignCurrentDate3
{
self.currentDate3 = [NSDate date];
}
-(void) assignCurrentDate4
{
currentDate4 = [[NSDate alloc]init];
//[[NSDate alloc]init] is not autoreleased.
}
-(IBAction) printDate
{
NSLog ("%@", currentDate1);
NSLog ("%@", currentDate2);
NSLog ("%@", currentDate3);
NSLog ("%@", currentDate4);
}
- (void)dealloc
{
[currentDate1 release];
[currentDate2 release];
[currentDate3 release];
[currentDate4 release];
[super dealloc];
}