2015-12-13 23 views
1

我正在用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") 
    } 

我的問題

  1. 是否有OC使用的NSTimer的iOS9.2任何錯誤?我用Google搜索了很多,但是如果你想讓計時器正常工作,我沒有發現任何說它是必需的。 How do I use NSTimer?

  2. NSTimer OC和Swift的用法不同嗎?

回答

0

用Objective-C的,你應該試試這個方法:

NSTimer *timer = [NSTimer scheduleTimerWithTimeInterval:2 target:self userinfo:...]; 

你可以看到所有方法的Xcode中的內容。

2

首先,您正在使用不同的方法。你怎麼會得到相同的結果? scheduledTimerWithTimeInterval將在初始化後自動添加到NSRunLoop。但是,timerWithTimeInterval不會。您需要手動撥打fire或將其添加到NSRunLoop才能觸發它。

就像方法的名字的意思,scheduledTimerWithTimeInterval會爲你做安排。至於timerWithTimeInterval,它只是給你一個計時器。蘋果的名字很受限制。有時候,你可以基於它猜測它的目的。