我想取 4 个随机数并将其保存到一个NSSet
中(以确保数组中没有相同的数字)
由于int
值必须是对象NSNumber
因此无法比较,因此无法在数组中保存唯一的整数。
+(NSMutableSet *)uniquenumber
{
int j=0;
NSMutableSet *sets=[[NSMutableSet alloc]init];
while (sets.count<4) {
j=arc4random()%7;
[sets addObject:[NSNumber numberWithInteger:j]];
}
return sets;
}
我想从0-7
中随机获取 4 个唯一编号。这就是问题所在。
感谢您对改进代码的帮助和建议。
正如@Marc莫斯比所建议的那样,我编辑了我的答案:
更新的答案:
int j = 0;
NSMutableSet *set= [NSMutableSet set];
while (set.count < 4) {
j = arc4random_uniform(7);
[set addObject:@(j)];
}
NSArray *array = set.allObjects;
这段代码很好。 如果NSNumber
已存在相等的值,则不会添加到NSMutableSet
。如果不确定,请看这里: NSMutableSet 包含重复项