Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Schedule Method call in Objective C

I am try to do multi-threading in Objective C. What I want to do now is that, for some instance of objects, I want to have to way to call some function 5 seconds later. How can I do that?

In Coco 2D, it's very easy to do it. They have something called scheduler. In Objective C, how to do it please?

Thanks

like image 280
privateson Avatar asked Jun 16 '10 21:06

privateson


People also ask

How do you delay a call method?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


2 Answers

You can use performSelector:withObject:afterDelay:

For example:

[self performSelector:@selector(myFunc:) withObject:nil afterDelay:5.0];
like image 87
Philippe Leybaert Avatar answered Oct 12 '22 04:10

Philippe Leybaert


Adding to what has been said, if you'd like to pass a single argument to myFunc, the call could be modified as follows

[self performSelector:@selector(showNote:) withObject:@"S" afterDelay:1.0];

and if you need to invoke a method that takes more than 1 argument, you can do that using invocation as shown in the following snippet -

SEL selector = @selector(nextPicture:);
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];

//Set the arguments
[invocation setTarget:self];
NSString* str = [imageNames objectAtIndex:1];
[invocation setArgument:&str atIndex:2];
[NSTimer scheduledTimerWithTimeInterval:5.0f invocation:invocation repeats:NO];
like image 37
Madhav Sbss Avatar answered Oct 12 '22 05:10

Madhav Sbss