2013-05-09 52 views
1

我在一個類中有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]; 
} 

分爲以下幾個方法我想從這些方法7隨機調用一個方法。

-(void)poemRandom{ 

     //Call a method randomly from those 7 methods 

} 

我該怎麼做?先謝謝您的幫助。

+0

這是什麼意思「隨機」在這裏? – Bhavin 2013-05-09 06:54:47

+6

而不是隨機調用一個方法,因爲他們都做同樣的工作(在數據只是一些差別),可以封裝數據,並隨機挑選其中一組數據,以顯示代替。 – nhahtdh 2013-05-09 06:58:17

回答

1

一個草率的方式行做到這一點:

-(void)poemRandom{ 
    int nr = arc4random() % 7; 
    if (nr == 0) [self poemAbcd]; 
    else if (nr == 1) [self poemHumptyDumpty]; 
    else if (nr == 2) [self poemBlackship]; 
    //and so on 
} 

希望它可以幫助

+0

非常感謝你兄弟。 – Leo 2013-05-09 07:10:55

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]; 
+3

你不能這樣做,因爲SEL不是objc對象。然而可以有'SEL陣列[7]' – 2013-05-09 07:01:56

+0

...和你必須添加INT randomIndex = arc4random()%[functionsArray計數]; – 2013-05-09 07:02:06

+0

@xlc,感謝您的更正。隨機數是一個微不足道的,所以我決定從示例代碼中排除它。 – Alexander 2013-05-09 07:04:26

0

使用

NSUInteger N = whatever; 
NSUInteger randomIndex = arc4random_uniform((u_int32_t)N); 

得到你的統一隨機指數。

然後使用該訪問函數指針陣列,或優選地只使用索引來創建數據本身,@nhahtdh評價建議(聽起來比較容易的方式)。