我怎么能随意播放视频而不重复

时间:2013-03-18 12:16:35

标签: iphone ios ipad nsmutabledictionary

我有一个应用程序,在提示时需要播放多个视频,但我希望这些视频是随机的,不会重复。

我目前的计划是创建一个NSMutableDictionary,其中键是视频的编号,该值只是一个基本字符串,告诉我它是否已被播放。然后,当要播放视频时,我会随机选择一个并查看是否已播放。像这样:

int randomNumber;
randomNumber = (arc4random() % 150) + 1;
if ([[videoDictionary valueForKey:[NSString stringWithFormat:@"%d", randomNumber]] isEqual:@"Played"])
{
   // This video has been played before. Make another random number and try again
} else {
   // This video has not been played before. Set the dictionary value to 'Played' and play the video
}

有更好的方法吗?有超过100个视频,当90%的视频已经播放时,这可能会开始有点愚蠢。

3 个答案:

答案 0 :(得分:4)

将您的字典副本创建为NSMutableDictionary。

按arc4random选择,播放。

从字典中删除它。

NSInteger randomNumber=arc4random();
NSMutableDictionary *playingVideo=[NSMutableDictionary dictionaryWithDictionary:videoDictionary];
//select a video from playingVideo
NSString *key= [NSString stringWithFormat:@"%d", randomNumber];
// ....
//remove from there
[playingVideo removeObjectForKey:key]; 

编辑1:

因为这是生成随机数并在字典中搜索。它可能不存在或已经被替换,甚至在1000次迭代中也不会生成特定数字。

所以在这种情况下你可以这样做:

NSMutableDictionary *playingVideo=[NSMutableDictionary dictionaryWithDictionary:videoDictionary];
while(playingVideo.count){
    NSMutableArray *keys=[playingVideo allKeys];
    NSInteger randomNumber=arc4random()%keys.count;
    NSString *key=[NSString stringWithFormat:@"%d", keys[key]];
    NSString *videoToPlay=playingVideo[key];
    //play it
    [playingVideo removeObjectForKey:key];
} 

答案 1 :(得分:3)

  • 创建一个包含所有数字的可变数组。
  • 随机播放元素(What's the Best Way to Shuffle an NSMutableArray?
  • 获取数组中的第一个元素并播放视频
  • 删除数组中的第一个元素
  • 当数组为空时重新创建并再次随机播放

采用这种方法,你不会在90%时得到同样的“愚蠢”。

答案 2 :(得分:1)

使用随机数时,应确保使用从低到高的随机数。

(arc4random() % 10) + 1; // it will produce random number from 1 to 10