2015-10-16 60 views
0

情境我需要一種方法來每秒觸發一次。我還需要能夠隨時停止該方法的解除。目前我使用的是NSTimerObjective-C:每秒調用方法的最佳做法

守則

self.controlTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updatePlayer) userInfo:nil repeats:YES]; 

問題我確信我可以使用NSTimer實現這一功能,並呼籲invalidate時,我希望它停止,但是我很擔心在UITableViewCell中放置NSTimer的性能開銷。

問題有沒有人知道每秒調用一個方法的更輕量級的選擇?

+0

nstimer是我們唯一的選擇! performnace不會影響你多久給你打電話的方法,但你的方法有什麼。只要你在你的方法中正確地維護你的代碼,你不必擔心每1秒調用一次。我這樣說是因爲我每0.1秒就會調用一次我的方法,並且我看到在完成的動畫中存在相當大的滯後。但我認爲如果是1秒,那就不會有任何問題 –

+2

'NSTimer'幾乎可以輕鬆得到,你需要多少個定時器?也許一個定時器每秒廣播一個'NSNotification'是一個更好的解決方案? – JustSid

+4

對代碼的性能進行假設通常不是一個好主意,因爲我們人類在這類事情上很糟糕。實施它並看看。 – dandan78

回答

3

我用的UITableViewCellNSTimer實例和UICollectionViewCell定製子類做你在做什麼,但我創建了一個協議PLMMonitor提供關於我的細胞-startMonitoring-stopMonitoring合同開始/停止(參見:invalidate)任何定時機制。

議定書

(顯然協議名稱前綴可以容易地改變)

@protocol PLMMonitor <NSObject> 

@required 

- (void)startMonitoring; 
- (void)stopMonitoring; 

@end 

使用細胞可見性來控制定時器

然後我可以利用-[UITableViewDataSource tableView:cellForRowAtIndexPath:]-[UICollectionViewDelegate collectionView:willDisplayCell:forItemAtIndexPath:]如果它符合協議,則在該單元上調用-startMonitoring(允許m在UITableView/UICollectionView ixed細胞):

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if ([cell conformsToProtocol:@protocol(PLMMonitor)]) 
    { 
     [(UICollectionViewCell<PLMMonitor> *)cell startMonitoring]; 
    } 
} 

然後我使用的-[UITableViewDelegate tableView:didEndDisplayingCell:forRowAtIndexPath:]-[UICollectionViewDelegate collectionView:didEndDisplayingCell:forItemAtIndexPath:]調用-stopMonitoring對細胞是否符合協議(再次允許混合的細胞在UITableView/UICollectionView):

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if ([cell conformsToProtocol:@protocol(PLMMonitor)]) 
    { 
     [(UICollectionViewCell<PLMMonitor> *)cell stopMonitoring]; 
    } 
} 

使用視圖控制器可視性,控制定時器

您還應該添加代碼-viewWillAppear-viewWillDisappear對符合協議,以保證定時器的可見細胞-startMonitoring-stopMonitoring開始/適當地停止時,他們不再可見:

- (void)viewWillAppear 
{ 
    for (UICollectionViewCell *aCell in [self.collectionView visibleCells]) 
    { 
     if ([aCell conformsToProtocol:@protocol(PLMMonitor)]) 
     { 
      [(UICollectionViewCell<PLMMonitor> *)aCell startMonitoring]; 
     } 
    } 
} 

- (void)viewWillDisappear 
{ 
    for (UICollectionViewCell *aCell in [self.collectionView visibleCells]) 
    { 
     if ([aCell conformsToProtocol:@protocol(PLMMonitor)]) 
     { 
      [(UICollectionViewCell<PLMMonitor> *)aCell stopMonitoring]; 
     } 
    } 
} 

性能影響/ NSTimers的能源使用

一種方法可以減少影響NSTimer實例具有電池壽命等等,是利用它們的tolerance屬性,它允許iOS執行some power savings magic with them while sacrificing a strict firing interval

替代定時器/觸發機制

+0

糟your你的真棒。 –

2

NSTimer非常輕便。您只需確保在單元重新使用時正確處理單元的定時器。