0

我已经编写了程序,它从数组中选择一个随机元素。

按下“开始”按钮后,如何循环该代码?

我想,一旦按下“开始”按钮,就会每 5 秒从数组中选择一个新元素并将其写入文本字段......感谢您的回答。

@implementation MARandom

- (IBAction)Start:(id)sender {

    NSArray *tones;

    tones = [NSArray arrayWithObjects: @"F#0", @"Gb0", @"G0", @"G#0",@"Ab0",@"A0",@"A#0",@"Bb0",@"B0",
            @"C1",@"C#1",@"Db1",@"D1",@"D#1",@"Eb1",@"E1",@"F1",@"F#1",@"Gb1",@"G1",@"G#1",@"Ab1",@"A1",@"A#1",@"Bb1",@"B1",
            @"C2",@"C#2",@"Db2",@"D2",@"D#2",@"Eb2",@"E2",@"F2",@"F#2",@"Gb2",@"G2",@"G#2",@"Ab2",@"A2",@"A#2",@"Bb2",@"B2",
            @"C3",@"C#3",@"Db3",@"D3",@"D#3",@"Eb3",nil];

    i= (arc4random() % 48);

        NSString *Tone; 
        Tone = [tones objectAtIndex: i];

        [TextField setStringValue:(NSString *)Tone];
    }
4

1 回答 1

0

请试试这个:

- (IBAction)Start:(id)sender {
[NSTimer scheduledTimerWithTimeInterval:5.0
                                 target:self
                               selector:@selector(updateTextFieldWithRandomNumber)
                               userInfo:nil
                                repeats:YES];
}

-(void)updateTextFieldWithRandomNumber{
NSArray *tones;

tones = [NSArray arrayWithObjects: @"F#0", @"Gb0", @"G0", @"G#0",@"Ab0",@"A0",@"A#0",@"Bb0",@"B0",
         @"C1",@"C#1",@"Db1",@"D1",@"D#1",@"Eb1",@"E1",@"F1",@"F#1",@"Gb1",@"G1",@"G#1",@"Ab1",@"A1",@"A#1",@"Bb1",@"B1",
         @"C2",@"C#2",@"Db2",@"D2",@"D#2",@"Eb2",@"E2",@"F2",@"F#2",@"Gb2",@"G2",@"G#2",@"Ab2",@"A2",@"A#2",@"Bb2",@"B2",
         @"C3",@"C#3",@"Db3",@"D3",@"D#3",@"Eb3",nil];

i= (arc4random() % 48);

NSString *Tone; 
Tone = [tones objectAtIndex: i];

[TextField setStringValue:(NSString *)Tone];
}

并且还考虑在一个地方准备数组,而不是在 viewDidLoad 处重复调用的代码。

注意:未经测试的代码,但应该可以工作。

于 2011-09-19T19:53:50.200 回答