Objective c NSTimer与OC之间有任何错误或更改吗?

Objective c NSTimer与OC之间有任何错误或更改吗?,objective-c,cocoa-touch,timer,nstimer,Objective C,Cocoa Touch,Timer,Nstimer,我正在用OC和Swift测试NSTimer。当我使用OC编写时,有一点我不太明白:是否需要在计时器初始化后将计时器添加到nsrunlop?如果不是必需的,为什么即使我将repeats设置为YES,也不能在循环中调用它 这是我的代码,我只是初始化了一个计时器,并将repeats设置为YES,我期望的是代码timerTick:应该每2秒调用一次,但它没有像我期望的那样工作。。。直到我将计时器添加到nsrunlop OC: -(void)viewDidLoad { [super viewDid

我正在用OC和Swift测试NSTimer。当我使用OC编写时,有一点我不太明白:是否需要在计时器初始化后将计时器添加到nsrunlop?如果不是必需的,为什么即使我将repeats设置为YES,也不能在循环中调用它

这是我的代码,我只是初始化了一个计时器,并将repeats设置为YES,我期望的是代码
timerTick:
应该每2秒调用一次,但它没有像我期望的那样工作。。。直到我将计时器添加到nsrunlop

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");
}
我用Swift重写了相同的代码 如您所见,我没有将计时器添加到
nsrunlop
,但它的工作方式与我预期的一样:每隔2秒调用
runTimeCode
方法

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")
    }
我的问题

  • NSTimer的iOS9.2在OC中是否存在任何错误?我用谷歌搜索了很多,但是我没有发现任何东西说如果你想让计时器正常工作,它是必需的。

  • OC和Swift之间的
    NSTimer
    用法是否不同


  • 对于Objective-C,您应该尝试以下方法:

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

    您可以在Xcode中看到所有方法的内容。

    首先,您使用的是不同的方法。你怎么会得到同样的结果<代码>scheduledTimerWithTimeInterval将在初始化后自动添加到
    nsrunlop
    。但是,
    timerWithTimeInterval
    不会。您需要手动调用
    fire
    或将其添加到
    nsrunlop
    以触发它

    就像这些方法的名称一样,
    scheduledTimerWithTimeInterval
    将为您进行调度。至于
    timerWithTimeInterval
    ,它只是给你一个计时器。苹果公司在名称上有很大的限制。有时,你可以根据它猜测它的用途