SNV7
SNV7

Reputation: 2593

Update a UILabel twice in the same method

I'm having some trouble figuring out hot to update a UILabel twice in one action. Basically the user hits a play button to hear a sound. While the sound is playing "message 1" appears in the UILabel. When the sound is done playing "Message 2" appears in the same label. When I run this the label goes directly to "message 2".

.h

@interface ViewController : UIViewController
<AVAudioRecorderDelegate, AVAudioPlayerDelegate>
{
AVAudioPlayer *audioPlayer;
UIButton *playButton;
UILabel *answerLabel;

}
@property (nonatomic, retain) IBOutlet UIButton *playButton;
@property (nonatomic, retain) IBOutlet UILabel *answerLabel;
-(IBAction) play;
@end

.m

-(IBAction) play
{    
        int length = [audioPlayer duration];
        [audioPlayer play];
        answerLabel.text = @"Message 1";
        [NSThread sleepForTimeInterval:length];
        answerLabel.text = @"Message 2";   
}

Upvotes: 2

Views: 139

Answers (2)

Simon Goldeen
Simon Goldeen

Reputation: 9080

I see you implement the AVAudioPlayerDelegate protocol, so I assume that at some point you set the delegate of the player to self

If that is the case, change your play method to the following:

-(IBAction) play
{    
    [audioPlayer play];
    answerLabel.text = @"Message 1";
}

Then implement this method:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    answerLabel.text = @"Message 2";
}

Upvotes: 5

MByD
MByD

Reputation: 137282

An update to the UI occurs only once the UI thread is unblocked, when it sleeps it is still blocked, so the first label never appears.

What you can do is:

answerLabel.text = @"Message 1";
[answerLabel performSelector:@selector(setText:) withObject:@"Message 2" afterDelay:length];

Upvotes: 2

Related Questions