1.
scheduled開頭和非schedule的開頭方法的區別。系統框架提供了幾種創建NSTimer的方法,其中以scheduled開頭的方法會自動把timer加入當前run loop,到了設定的時間點就會觸發指定的方法,而沒有scheduled開頭的方法則需要程序員自己手動添加到timer到一個run loop中才會有效。run loop在運行時一般有兩個mode,一個defaultmode,一個trackingmode,正常情況下run loop使用defaultmode,scheduled生成的timer會默認添加到defaultmode中,當我們互動scrollview時,run loop切換到trackingmode運行,于是我們發現定時器失效了。為了使定時器在我們滑動scrollview時也能正常運行,我們需要確保defaultmode和trackingmode里都添加了我們生成的timer。如:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(addone) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
或者:
NSTimer *timer = [NSTimer timerWithTimeInterval:_timeInterval target:self selector:@selector(addone) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
2.
使用NSTimer時,timer會保持對target和userInfo參數的強引用。只有當調取了NSTimer的invalidate方法時,NSTimer才會釋放target和userInfo。生成timer的方法中如果repeats參數為NO,則定時器觸發后會自動調取invalidate方法。如果repeats參數為YES,則需要程序員手動調取invalidate方法才能釋放timer對target和userIfo的強引用。
3.
在使用repeats參數為YES的定時器時,如果在使用完定時器時后沒有調取invalidate方法,導致target和userInfo沒有被釋放,則可能會形成循環引用情況,從而影響內存釋放。