Orpheus Mercury
Orpheus Mercury

Reputation: 1627

Timed, looping text output on iPhone

I'm creating an app that displays a random word (a key from an NSDictionary) in a UILabel and a list of associated words (an NSArray that is the displayed key's value) in another UILabel when the user pushes a button. For example: if the user pushes the button, the main word might be "Cat" and the list would be something like "lion", "snow leopard", "tiger".

I'd like to loop the text output so that the user pushes the button once, gets a word and a list, there's a timed pause, and then the word and list refresh. Here's the method I have so far:

- (IBAction)changeWord:(UIButton*)sender {
        //next line displays the randomly selected NSDictionary key, such as "Cat" in a label
        self.label.text = [self.dictionary selectKey];
        //next two lines displays the value associated with the selected key (an array), such as "lion", "snow leopard", "tiger" in another label
        NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
        self.listLabel.text = labelText;
       }

That obviously doesn't loop and simply displays new output for both labels whenever the button is pressed. I thought that creating a for loop that loops as many times as there are dictionary keys would solve half of the problem:

- (IBAction)changeWord:(UIButton*)sender {

    //next line counts the keys in the NSDictionary
    NSInteger numberOfKeys = [self.dictionary CountKeys];
   for( int index = 0; index < numberOfKeys; index++ ) 
   {
    self.label.text = [self.dictionary selectKey];
    NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
    self.listLabel.text = labelText;
   //need some type of timer here! 
   }

But I need some type of timer that will pause the display at a regular interval before its refreshed. That's where I'm stuck!

Does anyone have any pointers?

Thanks very much!

Upvotes: 0

Views: 146

Answers (1)

sch
sch

Reputation: 27506

You can use the method performSelector:withObject:afterDelay\] of NSObject:

- (IBAction)changeWord:(UIButton*)sender
{
    [self changeWord];
}

- (void)changeWord
{
    if (musicStopped) return;

    //next line displays the randomly selected NSDictionary key, such as "Cat" in a label
    self.label.text = [self.dictionary selectKey];
    //next two lines displays the value associated with the selected key (an array), such as "lion", "snow leopard", "tiger" in another label
    NSString *labelText = [[NSString alloc] initWithFormat:@"%@", [self.dictionary selectList]];
    self.listLabel.text = labelText;

    // Add this line
    [self performSelector:@selector(changeWord) withObject:nil afterDelay:30.0];
}

Upvotes: 2

Related Questions