如何使用NSTimer在Objective-C中每隔x秒调用一个方法?

时间:2022-07-07 01:07:00

I am using Objective-C, Xcode 4.5.1 and working on an app for the iPhone.

我正在使用Objective-C,Xcode 4.5.1并开发适用于iPhone的应用程序。

I have a method A in which I want to call another method B to do a series of calculations every x seconds. In method A I start playing an audio file. Method B will monitor the audio every x seconds for the duration of the audio file.

我有一个方法A,其中我想调用另一个方法B每隔x秒进行一系列计算。在方法A中,我开始播放音频文件。方法B将在音频文件的持续时间内每隔x秒监视音频。

I have found NSTimer as a potential solution, but am having a hard time getting it to work/understanding it.

我发现NSTimer是一个潜在的解决方案,但我很难让它工作/理解它。

I simply want to call Method B every x seconds and run its calculations, but NSTimer requires me to provide several things of which I'm not sure what I'm supposed to tell it.

我只是想每隔x秒调用一次方法B并运行它的计算,但是NSTimer要求我提供一些我不确定我应该告诉它的东西。

[NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval) 
target:(id) select:(SEL) userInfo:(id) repeats:(BOOL)];

It is my understanding that at NSTimeInterval I provide the interval at which I want NSTimer to operate. But, how do I tell it to run Method B?

据我所知,在NSTimeInterval中我提供了我希望NSTimer运行的时间间隔。但是,我如何告诉它运行方法B?

I have looked at example code, and am currently under the impression that I provide the method at the 'select:'. But, what do I write at the 'target:'? Why would I need a target? I tried entering 'self', but Xcode tells me:

我查看了示例代码,目前我的印象是我在'select:'处提供了方法。但是,我在'目标:'写什么?我为什么需要目标?我尝试输入'self',但Xcode告诉我:

Use of undeclared identifier 'self'

使用未声明的标识符'self'

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self 
select:@selector(targetMethod:myVolumeMonitor()) userInfo:nil repeats:YES];

So, I figure 'self' is supposed to be a pointer to an object, but where do I want to point to?

所以,我认为'self'应该是指向对象的指针,但我想指向哪里?

Below is a simplification of my code:

以下是我的代码的简化:

MethodA()
{
//Start playing an audio file.

//NSTimer calling Method B, as long the audio file is playing, every x seconds.
}

MethodB()
{
//Do calculations.
}

I would be grateful if somebody could provide me with some answers/point me in the right direction! (:

如果有人能给我一些答案/指出我正确的方向,我将不胜感激! (:

4 个解决方案

#1


35  

Target is the recipient of the message named in select. In Objective-C functions are not called. There are rather messages sent to objects. The Object internally refers to its symbol table and determines which of its methods is being called. That is a selector. Your selector is @selector(MethodB). (BTW: you should start method names with lower case. "methodB" would be more appropriate here.) This leads to the question: how to determine the object to which the message is sent? That is the target. In your case, it is simply self.

Target是select中指定的消息的接收者。在Objective-C中,不调用函数。相反,消息发送到对象。 Object内部引用其符号表并确定调用哪个方法。那是一个选择器。您的选择器是@selector(MethodB)。 (顺便说一下:你应该用小写字母开始方法名称。“methodB”在这里更合适。)这导致了一个问题:如何确定消息发送到的对象?那就是目标。在你的情况下,它只是自我。

BTW: In this case the selector is expected to return void and accept an id, which is the id of the NSTimer object itself. That will come handy if you want the timer to stop firing based on some conditions according to your program logic. Most important: Your selector is then methodB: rather than methodB.

BTW:在这种情况下,期望选择器返回void并接受一个id,它是NSTimer对象本身的id。如果您希望计时器根据您的程序逻辑根据某些条件停止触发,那么这将非常方便。最重要的是:你的选择器是methodB:而不是methodB。

- (void) methodA
{
//Start playing an audio file.

//NSTimer calling Method B, as long the audio file is playing, every 5 seconds.
[NSTimer scheduledTimerWithTimeInterval:5.0f 
target:self selector:@selector(methodB:) userInfo:nil repeats:YES];
}

- (void) methodB:(NSTimer *)timer
{
//Do calculations.
}

#2


5  

try this

尝试这个

 NSTimer *aTimer = [NSTimer timerWithTimeInterval:(x) target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

    NSRunLoop *runner = [NSRunLoop currentRunLoop];
    [runner addTimer:aTimer forMode: NSDefaultRunLoopMode];  
    [popUpImageView release];

- (void)timerFired:(NSTimer*)theTimer 
{
if(condition)
{
  [theTimer isValid]; //recall the NSTimer
   //implement your methods
}
else
{
  [theTimer invalidate]; //stop the NSTimer

}

}

#3


5  

Well you are trying to call an normal C method, NSTimer can't to that.

好吧,你试图调用一个普通的C方法,NSTimer不能这样做。

The target is the an instance of the class on which to call the selector, this selector adn not select. The selector here is a SEL type which you can create with the @selector(METHOD_NAME) function.

目标是要调用选择器的类的实例,此选择器不能选择。此处的选择器是SEL类型,您可以使用@selector(METHOD_NAME)函数创建该类型。

For example this will call the handleTimer : ever 0.1 second: (For this example the AppDelegate is used):

例如,这将调用handleTimer:永远0.1秒:(对于此示例,使用AppDelegate):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //SNIP, some code to setup the windos.   

    [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
    return YES;
}

- (void) handleTimer:(NSTimer *)timer {
    // Hanlde the timed event.
}

#4


4  

If you look at your code and compared to the one below

如果您查看代码并与下面的代码进行比较

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
select:@selector(targetMethod:myVolumeMonitor()) userInfo:nil repeats:YES];

self means that you are invoking a method in same instance of your class, in your example the method is myVolumeMonitor

self表示您在类的同一实例中调用方法,在您的示例中,方法是myVolumeMonitor

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(MethodB) userInfo:nil repeats:YES];

and you are good to go though

你很高兴

method be should look like this

方法应该是这样的

- (void)MethodB:(NSTimer*)timer { 
// do something
}

#1


35  

Target is the recipient of the message named in select. In Objective-C functions are not called. There are rather messages sent to objects. The Object internally refers to its symbol table and determines which of its methods is being called. That is a selector. Your selector is @selector(MethodB). (BTW: you should start method names with lower case. "methodB" would be more appropriate here.) This leads to the question: how to determine the object to which the message is sent? That is the target. In your case, it is simply self.

Target是select中指定的消息的接收者。在Objective-C中,不调用函数。相反,消息发送到对象。 Object内部引用其符号表并确定调用哪个方法。那是一个选择器。您的选择器是@selector(MethodB)。 (顺便说一下:你应该用小写字母开始方法名称。“methodB”在这里更合适。)这导致了一个问题:如何确定消息发送到的对象?那就是目标。在你的情况下,它只是自我。

BTW: In this case the selector is expected to return void and accept an id, which is the id of the NSTimer object itself. That will come handy if you want the timer to stop firing based on some conditions according to your program logic. Most important: Your selector is then methodB: rather than methodB.

BTW:在这种情况下,期望选择器返回void并接受一个id,它是NSTimer对象本身的id。如果您希望计时器根据您的程序逻辑根据某些条件停止触发,那么这将非常方便。最重要的是:你的选择器是methodB:而不是methodB。

- (void) methodA
{
//Start playing an audio file.

//NSTimer calling Method B, as long the audio file is playing, every 5 seconds.
[NSTimer scheduledTimerWithTimeInterval:5.0f 
target:self selector:@selector(methodB:) userInfo:nil repeats:YES];
}

- (void) methodB:(NSTimer *)timer
{
//Do calculations.
}

#2


5  

try this

尝试这个

 NSTimer *aTimer = [NSTimer timerWithTimeInterval:(x) target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

    NSRunLoop *runner = [NSRunLoop currentRunLoop];
    [runner addTimer:aTimer forMode: NSDefaultRunLoopMode];  
    [popUpImageView release];

- (void)timerFired:(NSTimer*)theTimer 
{
if(condition)
{
  [theTimer isValid]; //recall the NSTimer
   //implement your methods
}
else
{
  [theTimer invalidate]; //stop the NSTimer

}

}

#3


5  

Well you are trying to call an normal C method, NSTimer can't to that.

好吧,你试图调用一个普通的C方法,NSTimer不能这样做。

The target is the an instance of the class on which to call the selector, this selector adn not select. The selector here is a SEL type which you can create with the @selector(METHOD_NAME) function.

目标是要调用选择器的类的实例,此选择器不能选择。此处的选择器是SEL类型,您可以使用@selector(METHOD_NAME)函数创建该类型。

For example this will call the handleTimer : ever 0.1 second: (For this example the AppDelegate is used):

例如,这将调用handleTimer:永远0.1秒:(对于此示例,使用AppDelegate):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //SNIP, some code to setup the windos.   

    [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
    return YES;
}

- (void) handleTimer:(NSTimer *)timer {
    // Hanlde the timed event.
}

#4


4  

If you look at your code and compared to the one below

如果您查看代码并与下面的代码进行比较

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
select:@selector(targetMethod:myVolumeMonitor()) userInfo:nil repeats:YES];

self means that you are invoking a method in same instance of your class, in your example the method is myVolumeMonitor

self表示您在类的同一实例中调用方法,在您的示例中,方法是myVolumeMonitor

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(MethodB) userInfo:nil repeats:YES];

and you are good to go though

你很高兴

method be should look like this

方法应该是这样的

- (void)MethodB:(NSTimer*)timer { 
// do something
}