Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone objectiveC alloc/release question

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

like image 305
Iuliu Atudosiei Avatar asked Dec 29 '22 01:12

Iuliu Atudosiei


1 Answers

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

like image 52
deanWombourne Avatar answered Jan 15 '23 20:01

deanWombourne