在@implementation部分循环代码

时间:2011-09-19 18:46:15

标签: objective-c nstimer nsrunloop

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

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

我想,一旦按下“开始”按钮,就会选择数组中的新元素并每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];
    }

1 个答案:

答案 0 :(得分: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。

注意:未经测试的代码,但应该有效。