我正在用OC和Swift測試NSTimer。當我使用OC編寫代碼時,下面是我不太明白的事情:定時器被定位後是否需要將定時器添加到NSRunLoop中?如果不需要,即使將重複設置爲YES,爲什麼不能在循環中調用?OC與NSTimer中的任何錯誤或更改?
這是我的代碼,我只是初始化一個計時器,並將重複設置爲YES,我期望的是應該每2秒調用一次代碼timerTick:
,但它不工作,因爲我預計...直到我添加定時器到NSRunLoop。
OC:
-(void)viewDidLoad {
[super viewDidLoad];
NSTimer *timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
}
-(void) timerTick:(NSTimer*) timer{
NSLog(@"ticked,%@",@"aa");
}
我改寫了相同的代碼與斯威夫特 正如你所看到的,我不定時添加到NSRunLoop
,但它的工作原理如我所料:該runTimeCode
方法每2秒調用一次。
var timer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "runTimeCode", userInfo: nil, repeats: true)
}
func runTimeCode(){
NSLog("ticked")
}
我的問題
是否有OC使用的NSTimer的iOS9.2任何錯誤?我用Google搜索了很多,但是如果你想讓計時器正常工作,我沒有發現任何說它是必需的。 How do I use NSTimer?
是
NSTimer
OC和Swift的用法不同嗎?