我有一个包含80个json对象的数组。我想建立一个只有4个元素的新子数组(但是每次都由80个元素的较大数组填充),并且只有该json的特定键。
以下是我的代码:
[arr_sub removeAllObjects];
[arr_sub addObject:[[arr_main objectAtIndex:currentcount] valueForKey:@"e"]];
for(int i =1;i<=3;i++)
{
//int random = number between 1 to 80 -- how do i generate this ??
[arr_sub addObject:[[arr_main objectAtIndex:random] valueForKey:@"e"]];
}
如何生成0到79之间的随机索引?
最佳答案
要生成一个范围内的随机索引,请使用arc4random_uniform(range)
。
在您的情况下:
int random = arc4random_uniform(80);
使用
arc4random_uniform()
代替arc4random()
,与使用mod运算符一样,它没有偏差。也不要使用C函数rand()
,因为它的结果不是随机的。但是JSON在哪里? JSON是一种传输表示形式,在Objective-C中,主要集合类是
NSArray
和NSDictionary
。接收到的JSON通常通过NSJSONSerialization
类和诸如以下的方法转换为这些的组合:+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
关于ios - iOS:在特定范围之间生成随机数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23888259/