从NSArray获取一个不重复的随机对象 [英] Getting a random object from NSArray without duplication

查看:144
本文介绍了从NSArray获取一个不重复的随机对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含17个对象的 NSArray ,如下所示:

I have an NSArray with 17 objects, something like this:

NSArray *objArray = [[NSArray alloc]initWithObjects: @"1",@"2",@"3",@"4",@"5",@"6"
,@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17", nil];

int

int random = arc4random()%17+1;

我想从 NSArray NSUserDefaults )。

I want to get a random object from this NSArray without it being a duplicate, even if I closed the app (maybe by using NSUserDefaults).

我已经得到了所有的对象,我想为同一对象生成一个新的随机序列。

If I've gotten all the objects I want to generate a new random sequence for the same objects.

推荐答案

创建数组的可变副本,并且在从该数组进行随机选择后,删除该同一对象。当您想要保存数组时,保存可变数组本身,因此可以恢复在应用程序重新启动时停止的位置。这个小测试应用程序这样做,只是记录随机选择的值:

You could do this by making a mutable copy of the array, and after you make a random selection from that array, remove that same object. When you want to save the array, save the mutable array itself, so can resume where you left off when the app restarts. This little test app does that, and just logs the value of the random pick:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.objArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17"];
    self.mut = [self.objArray mutableCopy];
}

-(IBAction)pickNumber:(id)sender {
    int index = arc4random_uniform(self.mut.count);
     NSLog(@"%@", self.mut[index]);
    [self.mut removeObjectAtIndex:index];
    if (self.mut.count == 0) {
        self.mut = [self.objArray mutableCopy];
        NSLog(@"*******************");
    }
}

这篇关于从NSArray获取一个不重复的随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆