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
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.
You can use performSelector:withObject:afterDelay:
For example:
[self performSelector:@selector(myFunc:) withObject:nil afterDelay:5.0];
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With