随机调用一个方法

Leo*_*Leo 1 iphone objective-c ios

我在课堂上有7种方法.当我收到一条特定的消息时,我必须从这7种方法中随机调用一种方法.我的示例代码是:

-(void)poemAbcd{

    UIImage *image = [UIImage imageNamed: @"abcd_bg.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:80 with:220];
}

-(void)poemHumptyDumpty{

    UIImage *image = [UIImage imageNamed: @"humpty_dumpty.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:80 with:170];
}

-(void)poemBlackship{

    UIImage *image = [UIImage imageNamed: @"black_sheep.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:66 with:229];
}

-(void)poemRowRow{

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:144 with:211];
}

-(void)poemHappy{

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:144 with:211];
}

-(void)poemItsyBitsy{

    UIImage *image = [UIImage imageNamed: @"boat_bg.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:144 with:211];
}

-(void)poemTwinkleTwinkle{

    UIImage *image = [UIImage imageNamed: @"twincle_twincle_little_star.png"];
    [backgroundImage setImage:image];

    [self changeMumuPosition:70 with:222];
}
Run Code Online (Sandbox Code Playgroud)

在下面的方法中,我想从这7个方法中随机调用一个方法.

-(void)poemRandom{

      //Call a method randomly from those 7 methods

} 
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做?在此先感谢您的帮助.

Ale*_*der 6

一种方法是将函数指针添加到数组中并从那里选择一个.SEL是一种在objective-c中包装选择器的方法,所以你可以使用类似的东西

// edited, fixed data structure, props to xlc
// don't forget to set array size according to function count
SEL funcionsArray[7] = { @selector(poemAbcd), @selector(poemHumptyDumpty), /* etc */ };
// randomIndex is a randomly selected number from 0 to [number-of-selectors] - 1
SEL randomSel = funcionsArray[randomIndex];
[self performSelector:randomSel];
Run Code Online (Sandbox Code Playgroud)

  • 你不能这样做,因为`SEL`不是objc对象.但是你可以拥有`SEL array [7]` (3认同)