How to call a method every x seconds in Objective-C using NSTimer?

前端 未结 4 1804
鱼传尺愫
鱼传尺愫 2020-12-24 14:12

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

I have a method A in which I want to call another method B to do a series of calculations e

4条回答
  •  情话喂你
    2020-12-24 15:03

    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.

    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.

    - (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.
    }
    

提交回复
热议问题