2011-04-07 239 views
1

此代碼的問題是,while循環執行時,內存使用量不斷增加。我想知道爲什麼這段代碼在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] 
+0

[池漏極];使用分配工具查找何時出現問題 – 0xDE4E15B 2011-04-07 06:46:33

+0

正如我所提到的,while循環執行時內存會增加。還有什麼我可以從Allocations樂器中獲得的? – Dhawal 2011-04-07 06:54:05

+0

如果你看到去年的WWDC視頻,你會發現他們把autorelease池放在了一邊。這會在每個週期釋放任何自動釋放對象,從而減少內存消耗。 – rckoenes 2011-04-07 07:22:57

回答

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.... */ 
    } 
+0

您是否可以在此處發佈您的更改,以防其他人遇到同樣的問題並在Google上發現您的問題? – 2011-04-08 11:10:11

+0

本身並不是一個真正的問題 - 他正在運行一個循環儘可能快的緊密循環,並在該循環中創建自動釋放的對象。解決辦法是不要這樣做。 – gnasher729 2014-04-04 09:38:21

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] 
+0

嗨託尼,謝謝你的代碼,但問題依然存在。當它在while循環中時,內存保持安裝狀態。是的,看到這些代碼後,我對代碼感到尷尬。我對iOS仍然很陌生,希望能改善我的代碼風格。 – Dhawal 2011-04-07 10:00:24

+0

@Dhawal如果內存仍在增長,那麼問題可能不在您向我們展示的代碼中。或者你可能在樂器中挑出了錯誤的東西。 – 2011-04-18 12:50:22