How to select random method using perform selector?
-
13-06-2021 - |
Frage
In my application I use performSelector
to call methods. I have three different methods in my application, I want that randomly I assign one of these three methods to perform selector. Here is my code.
[self performSelector:@selector()];
Here is my three methods..
-(void)Act1
{
}
-(void)Act2
{
}
-(void)Act3
{
}
Now I want to assign each time one method randomly to selector. Can any one guide me how I can do this.
Lösung
This should do it:
int rand = (arc4random() % 3) + 1;
[self performSelector:NSSelectorFromString([NSString stringWithFormat:@"Act%d",rand])];
Andere Tipps
Use an array of selectors, SEL
is their type.
SEL mySelectors[3] = { @selector(Act1), @selector(Act2), @selector(Act3) };
[self performSelector:mySelectors[rand() % 3]];
You may want to suppress the warning issued by ARC about a potential memory leak, it's safe since your methods are void
. Use objc_msgSend
or wrap the code like this:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:mySelectors[rand() % 3]];
#pragma clang diagnostic pop
You could put 3 strings in an array representing your methods, pick randomly one and the use Nsselectorfromstring to get your selector
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow