views:

280

answers:

2

Hi, I am new to ObjectiveC language. I am having trouble understanding memory management syntax. My code is below:

NSDate* someDate;
someDate=[[NSDate alloc] init];
loop
{ 
   someDate=[[NSDate alloc] init];
}

will I have a memory leak here ? or the NSDate object returned is [autorelease]?

Thanks

+2  A: 

You will have many memory leaks. Objects are initially retained (not autoreleased) if they are returned by methods that have new, alloc or copy in the name. [NSDate date] would be autoreleased. If you post more substantive code I can give you some help in accomplishing your goal cleanly.

Also have a look at Apple's Memory Management Guide.

David Kanarek
So it has nothing to do with alloc?
willcodejavaforfood
You're right, I believe it is actually the alloc method that that causes the retain, but they are always used together so I'm not sure it matters, but I'll correct my post.
David Kanarek
I think he means methods that have alloc, new or copy in the name.
Mongus Pong
David.. thanks...here are more details.The main point of my code is to update the "someDate" variable with the "current date" in the loop.
Iuliu Atudosiei
@DavidKanarek - The alloc causes the retain count to be set to 1, not the init.
deanWombourne
@luliu I would use `someDate=[NSDate date]` and profile your application to make sure the memory usage is acceptable.
David Kanarek
A: 

Hi,

As @DavidKanarek says, you will have leaks.

There are a number of ways to fix these leaks :

NSDate* someDate;
someDate=[NSDate date];
loop
{ 
   someDate=[NSDate date];
}

or

NSDate* someDate=nil;
someDate=[[NSDate alloc] init];
loop
{ 
   [someDate release];
   someDate=[[NSDate alloc] init];
}

[someDate release];

The first one is easier code to read but the second one keeps your memory usage down as low as possible. If your loop is not too big, use the first. If you're going through the loop thousands of times, I'd use the second.

Sam

deanWombourne