Using NSDate in a While Loop

I want to get the current date using [NSDate date] in a While loop. I accomplish this by doing the following:

while (interval > 0.0) { NSDate *currentDate = [[NSDate alloc] init]; currentDate = [NSDate date]; interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60; [currentDate release]; } 

I do not know why memory leaks indicate that a large amount of memory is leaking. Tell me this is the right way to complete my task.

+4
source share
3 answers

The problem is not that you are flowing as such, but that you are working in a while loop.

Automatically issued dates grow in the auto-update pool, because the pool is empty only in idle mode in the execution cycle.

One solution is to create a local autostart pool within the while scope

  while (foo) { NSAutoreleasePool *aPool = [[NSAutoreleasePool alloc ] init]; NSDate *currentDate = [NSDate date]; // other computational foo [aPool release] } 

When you release the pool in the local area, it will immediately lose the requested auto-implemented date.

+3
source

In the line NSDate *currentDate = [[NSDate alloc] init]; you will create a new object that you must release. In the line currentDate = [NSDate date]; you are not releasing the old object, you are only pointing to a pointer to another object. In the line [currentDate release]; you release the object created in the second line of the loop, which can lead to an error (this object is marked as autorelease, and iOS will clear it for you). You should rewrite your code as follows:

 while (interval > 0.0) { NSDate *currentDate = [NSDate date]; interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60; } 
+6
source

You do not need the first line NSDate *currentDate = [[NSDate alloc] init]; . You can directly set the [NSDate] date to the current date.

 NSDate *currentDate = nil; while (interval > 0.0) { currentDate = [NSDate date]; interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60; } 
+4
source

All Articles