1

The problem with this code is that when the while loop is executing, the memory usage is increasing continuously. I want to know why does this code keeps on increasing memory when its in while loop. Which object here is eating the memory. What can i do so that the memory does not increase in the loop.

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSNumber *totalTime = [[self nowPlayingItem] valueForProperty:MPMediaItemPropertyPlaybackDuration];
while (self.currentPlaybackTime < [totalTime floatValue]) 
{
    NSNumber *currentTime = [[NSNumber alloc] initWithFloat:self.currentPlaybackTime];
    if([[NSThread currentThread] isCancelled])
    {
        [NSThread exit];
        [newThread release];
    }
    else if([totalTime intValue] - [currentTime intValue] == 1.0)  
    {
        if(currentTime)
            [currentTime release];
        break;
    }
    [currentTime release];
}
[pool release]
4

2 回答 2

0

我已经解决了这个问题。用 Timer 替换了 while 循环并进行了一些更改。创建了一个每秒触发的计时器

 timer = [NSTimer timerWithTimeInterval:1
                                target:self
                              selector:@selector(performAction)
                              userInfo:nil
                               repeats:YES];

然后在 performAction 中,检查当前播放时间并使计时器无效,因为时间差 <= 1 秒

int totalTime = [[[self nowPlayingItem] valueForProperty:MPMediaItemPropertyPlaybackDuration] intValue];
    if((totalTime - self.currentPlaybackTime) <= 1.0)
    {
        if(timer)
            [timer invalidate];

         /* Performed my desired action here.... */
    }
于 2011-04-08T06:54:28.420 回答
0

那是您那里的一些低效代码....这是一个不会无缘无故地分配内存的替代品,此外,您可能还想在那里休眠,这样它就不会占用CPU

// not needed any more
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

int totalTime = [[[self nowPlayingItem] valueForProperty:MPMediaItemPropertyPlaybackDuration] intValue];

while (self.currentPlaybackTime < totalTime) 
{
    //not needed any more
    //NSNumber *currentTime = [[NSNumber alloc] initWithFloat:self.currentPlaybackTime];
    if([[NSThread currentThread] isCancelled])
    {
        [NSThread exit];
        [newThread release];
    }
    else if((totalTime - self.currentPlaybackTime) <= 1.0)  // you may never hit 1
    {
        break;
    }
}
//[pool release]
于 2011-04-07T08:30:05.383 回答