开发者

xcode do a random method

Hi e开发者_如何学JAVAvery one I'm french so scuse me for my english. Well what I want to do is that every second I do a random method between four methods. how can I do this please ?


You want a random integer number between 1 and 4 and then a case statement to execute the corresponding selectors, right?


array of 4 strings (the names of your methods), generate random int between 0 and 3 then use NSSelectorFromString to call.


For example you have four methods:

//put them on array as strings
NSArray *arrayOfSelectors = [NSArray arrayWithObjects:@"eat", @"drink", @"run", @"sleep", nil];

//generate a random number based on the number of selectors inside the array
int randomNumber = arc4random()%arrayOfSelectors.count;

//call the method
//assumes that someObject really implement the methods inside the array, else your app will crash
[someObject performSelector:NSSelectorFromString([arrayOfSelectors objectAtIndex:randomNumber])];
  1. -(void)eat;
  2. -(void)drink;
  3. -(void)run;
  4. -(void)sleep;


Somewhere you need to start the timer

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(randomMethod:) userInfo:nil repeats:YES];

Then implement the method that will be called:

-(void)randomMethod:(NSTimer *)timer {

    if (shouldStop) {
        [timer invalidate];
        return;
    } 

    int rand = arc4random() % 4;

    switch (rand) {
        case 0: 
            [self method0];
            break;
        case 1:
            [self method1];
            break;
        case 2:
            [self method2];
            break;
        case 3:
            [self method3];
            break;
    }
}

then later, at some point if you want to stop it, set shouldStop to true.


First create the timer:

NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1.0
                                              target: self
                                            selector:@selector(selectorSwitcher:)
                                            userInfo: nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];

Then implement the switcher:

-(void)selectorSwitcher:(NSTimer *)timer {

    int randomNumber = 1+ arc4random() %(4);
    switch (randomNumber) {
        case 1:
            [self selector1];
            break;
        case 2:
            [self selector2];
            break;
        case 3:
            [self selector3];
            break;
        case 4:
            [self selector4];
            break;

        default:
            break;
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜