Xcode Can';t清除/重置NSMutableSet?

Xcode Can';t清除/重置NSMutableSet?,xcode,random,nsmutableset,Xcode,Random,Nsmutableset,这就是我想做的。每次启动viewDidLoad时,获取7个随机、不重复的数字。我用它来创建随机数,但我一直在尝试在NSMutableSet加载时清除它以获得一个新的集合,我遇到了麻烦。NSLog清楚地显示NSMutableSet中没有任何内容,但它总是以相同的顺序显示相同的数字 // Create set NSMutableSet *mySet = [NSMutableSet setWithCapacity:6]; // Clear set NSMutableSet *mutableSet =

这就是我想做的。每次启动viewDidLoad时,获取7个随机、不重复的数字。我用它来创建随机数,但我一直在尝试在NSMutableSet加载时清除它以获得一个新的集合,我遇到了麻烦。NSLog清楚地显示NSMutableSet中没有任何内容,但它总是以相同的顺序显示相同的数字

// Create set
NSMutableSet *mySet = [NSMutableSet setWithCapacity:6];

// Clear set
NSMutableSet *mutableSet = [NSMutableSet setWithSet:mySet];
[mutableSet removeAllObjects];
mySet = mutableSet;

NSLog(@"mutableSet: %@", mutableSet);  // Shows nothing
NSLog(@"mySet: %@", mySet);  // Shows nothing

// Assign random numbers to the set
while([mySet count]<=6){
    int Randnum = arc4random() % 7+1;
    [mySet addObject:[NSNumber numberWithInt:Randnum]];
}

NSLog(@"mySet1: %@", mySet);  // Always shows 5,1,6,2,7,3,4 ???
//创建集合
NSMutableSet*mySet=[NSMutableSet setWithCapacity:6];
//清晰设置
NSMutableSet*mutableSet=[NSMutableSet setWithSet:mySet];
[mutableSet removeAllObjects];
mySet=mutableSet;
NSLog(@“mutableSet:%@”,mutableSet);//什么也看不出来
NSLog(@“mySet:%@”,mySet);//什么也看不出来
//将随机数分配给集合
虽然([mySet count]一个
NS(可变)集合
是一个无序集合,但它不会保留插入元素时的顺序。因此,您的输出仅显示该集合包含 数字从1到7

您有不同的选项来获得预期的输出

  • 请改用
    NSMutableOrderedSet

  • 使用集合跟踪已发生的数字,但存储 数字也在一个数组中:

    NSMutableArray *numbers = [NSMutableArray array];
    NSMutableSet *mySet = [NSMutableSet set];
    while ([numbers count] < 6) {
        NSNumber *randNum = @(arc4random_uniform(7) + 1);
        if (![mySet containsObject:randNum]) {
            [numbers addObject:randNum];
            [mySet addObject:randNum];
        }
    }
    NSLog(@"numbers: %@", numbers);
    
    NSMutableArray*numbers=[NSMutableArray];
    NSMutableSet*mySet=[NSMutableSet];
    而([数字计数]<6){
    NSNumber*randNum=@(arc4random_-uniform(7)+1);
    if(![mySet containsObject:randNum]){
    [number addObject:randNum];
    [mySet addObject:randNum];
    }
    }
    NSLog(@“编号:%@”,编号);
    
  • 对于一个小的集合(如本例中的7个数字),您可以只使用一个数组:

    NSMutableArray *numbers = [NSMutableArray array];
    while ([numbers count] < 6) {
        NSNumber *randNum = @(arc4random_uniform(7) + 1);
        if (![numbers containsObject:randNum]) {
            [numbers addObject:randNum];
        }
    }
    NSLog(@"numbers: %@", numbers);
    
    NSMutableArray*numbers=[NSMutableArray];
    而([数字计数]<6){
    NSNumber*randNum=@(arc4random_-uniform(7)+1);
    如果(![numbers containsObject:randNum]){
    [number addObject:randNum];
    }
    }
    NSLog(@“编号:%@”,编号);
    

  • 我更喜欢阵列版本。谢谢!