我在我的应用程序类之一的方法中使用函数 random()%some integer,我不知道在哪里放置 srandom (time (NULL)) 以生成不是伪随机数而是真正的随机数。我已经将它放在 viewDidLoad 和 viewWillAppear 中,但它没有帮助。
- (NSMutableDictionary *)getUsersFromServer
{
srand(time(NULL));
//here we're getting list of users from the server
NSMutableDictionary * users = [[[NSMutableDictionary alloc] init] autorelease];
for (int i = 0;i < 19;i++)
{
int wins = rand()%100; float f_wins = (float)wins;
int losses = rand()%100; float f_losses = (float)losses;
int withdr = rand()%100; float f_withdr = (float)withdr;
float win_per = f_wins / ((f_wins + f_losses + f_withdr) / 100.0);
[userresults setArray:[NSMutableArray arrayWithObjects:[NSNumber numberWithInt:wins],
[NSNumber numberWithInt:losses],
[NSNumber numberWithInt:withdr],
[ NSNumber numberWithFloat:win_per],
nil]];
[users setObject:userresults forKey:[NSString stringWithFormat:@"Pfeffer ID %i",i]];
}
[userresults release];
return users;
}
像这样的东西......代码看起来很糟糕,但它的意义是可以理解的。rand() 为每次循环迭代产生相同的数字。如果我使用 arc4random() 它什么都不会改变。还是一样的数字