Reputation: 1349
I want to get the current date using [NSDate date] in a While Loop. I accomplish this by doing like this:
while (interval > 0.0) {
NSDate *currentDate = [[NSDate alloc] init];
currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
[currentDate release];
}
I dont know why is the Memory leaks shows that there is a great amount of memory is leaked. Kindly guide me that what is the right way to accomplish my task.
Upvotes: 4
Views: 1003
Reputation: 1826
The problem is not that you are leaking per se but that you are running in a while loop.
The auto released dates are growing in the autorelease pool because the pool only empties in the idle time on the run loop.
One solution is to create a local autorelease pool within the scope of the while
while (foo) {
NSAutoreleasePool *aPool = [[NSAutoreleasePool alloc ] init];
NSDate *currentDate = [NSDate date];
// other computational foo
[aPool release]
}
When you release the pool in the local scope it will immediately drop the autoreleased date you requested.
Upvotes: 3
Reputation: 51374
You don't need the first line NSDate *currentDate = [[NSDate alloc] init];
. You can directly assign the [NSDate date] to currentDate.
NSDate *currentDate = nil;
while (interval > 0.0) {
currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
}
Upvotes: 4
Reputation: 778
In line NSDate *currentDate = [[NSDate alloc] init];
you create a new object, which you should release. In line currentDate = [NSDate date];
you do not release an old object, you only make a pointer to point to another object. In line [currentDate release];
you release an object created on the second line of a loop, which may cause an error (that object is marked as autorelease one and iOS will clean it for you). You should rewrite your code like:
while (interval > 0.0) {
NSDate *currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
}
Upvotes: 6