Using NSDate in While loop

橙三吉。 提交于 2020-01-14 10:16:16

问题


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.


回答1:


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.




回答2:


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;
}



回答3:


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;
}


来源:https://stackoverflow.com/questions/6305287/using-nsdate-in-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!