在Objective C中每隔几秒重复一次方法

时间:2021-06-08 01:16:33

I have a method -(void)foo that I want to call once in viewDidAppear, then I want it to repeat every n seconds, where n is some integer. How can I do this?

我有一个方法 - (void)foo,我想在viewDidAppear中调用一次,然后我希望它每n秒重复一次,其中n是一个整数。我怎样才能做到这一点?

I tried this, but it's not repeating:

我尝试过这个,但不是重复:

[NSTimer scheduledTimerWithTimeInterval:7.0 target:nil selector:@selector(foo) userInfo:nil repeats:YES];

1 个解决方案

#1


17  

The problem is that target is nil.

问题是目标是零。

What this timer does is every 7 seconds it calls [nil foo], which does nothing.

这个计时器的作用是它每隔7秒调用[nil foo],它什么都不做。

If you want to call the method foo on the object that creates the timer, use target:self

如果要在创建计时器的对象上调用方法foo,请使用target:self

#1


17  

The problem is that target is nil.

问题是目标是零。

What this timer does is every 7 seconds it calls [nil foo], which does nothing.

这个计时器的作用是它每隔7秒调用[nil foo],它什么都不做。

If you want to call the method foo on the object that creates the timer, use target:self

如果要在创建计时器的对象上调用方法foo,请使用target:self