How to make a periodic call to a method in objective c?

限于喜欢 提交于 2019-11-29 11:19:47

You can create and schedule an instance of NSTimer to call your method on a given time interval. See in particular the following convenience creation method:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSTimer_Class/Reference/NSTimer.html

Your best bet is to look into Grand Central Dispatch since you are going to want to run this in the background:

Use NSTimer mentioned above.

What you want is the NSObject method -performSelector:withObject:afterDelay:.

Click for docs.

If you have the method that it calls call this on itself again, you'll have a looping, self-firing delayed poll method.

I'd recommend checking a class variable to see if you really mean it each time, so you can turn it off from outside itself.

Grand Central Dispatch will create a different thread to run on. so if the timer method (shown below and suggested above) lags your app you will need to put the command on a separate thread.

NSTimer is what you should use though. for example if you want to repeat a method that is initiated from a button press you could do this

- (void)viewDidLoad
{
    [super viewDidLoad];
    [cameraControlButtonUp addTarget:self action:@selector(cameraControlButtonUpPressed) 
          forControlEvents:UIControlEventTouchUpInside];
}

-(IBAction)buttonDown:(id)sender{
     NSInteger tag = [sender tag];

    if (tag==1) {  
        buttonCounter=1;
        timer = [[NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(sendJoin) userInfo:nil repeats:YES]retain];
    }
}

-(void)sendJoin
{
    switch (buttonCounter) {
        case 1:
            [cClient userDigitalPushAndRelease:372];
            break; 
        default:
            break;
    }
}

    -(void)cameraControlButtonUpPressed
    {
        [timer invalidate];
    }

that will repeat the command till the button is released. take in mind you need to link the ibaction with the button down event (only the button down event). as well as create timer in the .h and tag the button to 1 that you want to use this with.

for a more basic example; its quite simple. just create your method to call, timer and set repeat to YES. then call invalidate to stop it. i had to create a seperate method sendJoin because i couldnt get the numbers to pass correctly to the method. but if you dont have any parameters its even easier. just use the timer syntax to create it then invalidate it when ur done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!