我用的UITableViewCell
內NSTimer
實例和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。
替代定時器/觸發機制
nstimer是我們唯一的選擇! performnace不會影響你多久給你打電話的方法,但你的方法有什麼。只要你在你的方法中正確地維護你的代碼,你不必擔心每1秒調用一次。我這樣說是因爲我每0.1秒就會調用一次我的方法,並且我看到在完成的動畫中存在相當大的滯後。但我認爲如果是1秒,那就不會有任何問題 –
'NSTimer'幾乎可以輕鬆得到,你需要多少個定時器?也許一個定時器每秒廣播一個'NSNotification'是一個更好的解決方案? – JustSid
對代碼的性能進行假設通常不是一個好主意,因爲我們人類在這類事情上很糟糕。實施它並看看。 – dandan78