如何在iOS 5中运行多个循环和条件检查?

时间:2012-06-02 02:13:17

标签: iphone ios xcode ipad loops

我有一个适用于iPad iOS 5的程序,它可以读入MIDI,然后在音乐上及时显示键盘上的音符。它工作正常,但我试图添加一个"重复部分"函数从一个又一次重复从时间戳A到时间戳B的部分。

我已经能够将时间戳作为我的重复部分的边界工作,但我无法使重复工作正常。当我尝试重复一个部分时,我不再能够获得键盘动画了。我觉得这个问题需要超线程,但我不确定。我已经在伪代码中概述了我想要做的事情。

//Start Repeat Method
while (the repeat switch is toggled) {
     Stop music player.

     Set music player to the start point of the repeat.

     while (the current play point is before the end point of the repeat) {
          Check the current play point.
     }
}
//End Repeat Method

所以基本上,我想要做的是在用户点击一个将被一遍又一遍地调用的开关时触发一个方法,直到他们将其关闭。在该方法中,它将停止播放器,将其设置为重复的开始,播放重复,直到它在重复结束时看到它,然后重新开始该方法。

我并不认为这部分会像以前那样棘手。我遇到的另一个问题是,当我把它连接到一个开关时,它不允许我关闭它,它只是永远。

提前感谢您的建议。

**编辑

这是我到目前为止所拥有的。它允许我循环我的部分,但我的动画正在显示,我无法与UI交互,我必须使用Xcode中的停止按钮终止程序。

- (IBAction)playRepeat:(id)sender {
     if (repeatToggle.on) {
          MusicPlayerStop(player);
          playerIsPlaying = NO;

          MusicPlayerSetTime(player, sequenceRepeatStartTime);
          moviePlayerViewController.moviePlayer.currentPlaybackTime = rollRepeatStartTime;

          MusicPlayerStart(player);
          [moviePlayerViewController.moviePlayer play];
          playerIsPlaying = YES;

          float difference = rollRepeatEndTime - rollRepeatStartTime;
          [NSThread sleepForTimeInterval:difference];

          MusicPlayerStop(player);
          playerIsPlaying = NO;
          [moviePlayerViewController.moviePlayer pause];

          [self playRepeat:sender];
     }
     else if (!repeatToggle.on) {
          MusicPlayerStop(player);
          playerIsPlaying = NO;
     }
}

1 个答案:

答案 0 :(得分:2)

你的while循环会耗尽CPU,因为它一直在运行并且什么都不等。 将它放在分离的线程中可能有所帮助,但如果你的播放器不是线程安全的话,你需要锁定机制。

如果没有播放器本身的通知,就不会在正确的时间重复播放。您应检查您的MIDI播放器是否支持任何通知或委托回调,以便在游戏达到您指定的点时获得通知。

无论如何,我会提供可能适合你的出路。您可以使用计时器来检查播放器,可能每隔100毫秒做一次这样的事情。

-(void) repeatCheck {
    if (the repeat switch is ON) {
        if (the current play point is NOT before the end point of the repeat) {
            Stop music player.
            Set music player to the start point of the repeat.
        }
    }
    [self performSelector:_cmd withObject:nil afterDelay:0.1];
}

-(IBAction) repeatSwitchToggled {
    if (the repeat switch is ON) {
        [self repeatCheck];
    }
    else {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(repeatCheck) object:nil];
    }
}