Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain/copy of autoreleased objects

I want to make sure I understand the memory management correctly here. Is there any particular reason to use one of the assignCurrentDate methods over another here? Also, all of these result in no memory leaks, correct?

in the .h we have:

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;

in the .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];
}
like image 257
Cephi Avatar asked Feb 23 '23 20:02

Cephi


1 Answers

The rule of thumb when it comes to iOS memory management is:

For every alloc, retain, copy, or new, you must have a corresponding release or autorelease.

You are leaking in several places actually. In your header, you retain your date objects and then in your dealloc method you release them. That is correct. However, In your assignDate methods, you fail to release the copy or retained date. While [NSDate date] is autoreleased, you are retaining and copying them yourself.

There is no reason to use your assignCurrentDate methods. You can just do something like the following in your init method:

self.currentDate1 = [NSDate date];

That's it.

Edit: (Okay, that's not it.)

As Jim points out in the comments:

The retain in the header signifies that the synthesized setter for those properties will retain objects assigned to them. But if you look at the assign* methods, you'll see that only assignCurrentDate3 actually uses the property. The rest assign directly to the ivar, bypassing the synthesized setter, so they aren't retained upon assignment.

like image 157
Moshe Avatar answered Mar 06 '23 23:03

Moshe