Reputation: 679
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
Upvotes: 4
Views: 4496
Reputation: 4727
You will have lots memory leaks.
someDate
is a poninter variable and is assigned a block of memory that you allocate, in this case is [[NSDate alloc] init]
.
However, in the loop you assign your pointer variable to another memory bolck (someDate=[NSDate date]
)
The memory leak occurs as those memory blocks which have already allocated are unreleased.
Upvotes: 0
Reputation: 411
This object-ownership scheme is implemented through a reference-counting system that internally tracks how many owners each object has. When you claim ownership of an object, you increase it’s reference count, and when you’re done with the object, you decrease its reference count. While its reference count is greater than zero, an object is guaranteed to exist, but as soon as the count reaches zero, the operating system is allowed to destroy it.
http://rypress.com/tutorials/objective-c/memory-management
But in latest xcode it provide ARC (Automatic reference counting).
So It will manage reference count automatically .when class is deallocate it release memory for all object it content within .
Upvotes: 1
Reputation: 38475
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
Upvotes: 5
Reputation: 12613
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.
Upvotes: 4