1

このコードの問題は、whileループが実行されているときに、メモリ使用量が継続的に増加していることです。このコードがwhileループのときにメモリを増やし続ける理由を知りたいです。ここのどのオブジェクトが記憶を食べていますか。ループ内でメモリが増加しないようにするにはどうすればよいですか。

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

それはあなたがそこに持っているいくつかの非効率的なコードです....これは理由もなくメモリを精神的に割り当てない代替品です、さらにあなたはそれが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 に答える
0

私はこの問題を解決しました。whileループをTimerに置き換え、いくつかの変更を加えました。毎秒起動するタイマーを作成しました

 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 に答える