iphone - 我怎么能不重复地随机播放视频

标签 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% 已经播放时,这可能会开始变得有点愚蠢。

最佳答案

创建一个字典副本到 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];
} 

关于iphone - 我怎么能不重复地随机播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15476653/

相关文章:

ios - 如何在视频播放时显示 MPMoviePlayer 完成按钮?

iphone - 如何在 objective c 的 facebook 组上传图片

ios - Apple iOS 分发证书在重置后有一个新的私钥

ipad - 改变 iPad 方向,旋转状态栏,工具栏,但不是主视图

iphone - 将 Target 从 iPhone- 更新到 Universal-App

swift - 在 Split View 中,如何在 Swift 中确定应用程序的当前宽度?

ios - UIBarButtonItem选择到下一个ViewController

iphone - 设置最长录制持续时间,同时从 iphone 应用程序录制视频

ios - UISlider 需要有一个范围 1-5 并将其 self 对齐到最近的凹口

ios - 如何在不重建的情况下在 xcode 中运行单个单元测试方法?