在iPhone应用中如何使用随机数(How to Use Random Numbers in Your iPhone App)

来源:互联网 发布:免费网络代理服务器 编辑:程序博客网 时间:2024/05/17 07:48

原文地址:http://howtomakeiphoneapps.com/2009/05/how-to-use-random-numbers-in-your-iphone-app/

 

Would you like your iPhone app to be able randomly pick a number between 1 and 10 or to randomly select one string from a list?

Getting this done requires us to use the random function - a regular old C function. In this post, I am going to show you how to create an array of objects and then use a random number to select one object from the list.

FIrst, use the import statements to import these two libraries: stdlib and time. Put this code into the top of your file:

#import "stdlib.h"
#import "time.h"

Now, create an array and populate it with strings that will serve as our objects:

NSMutableArray *arrayOfObjects = [[NSMutableArray alloc] init];
[arrayOfObjects addObject:@"Object One"];
[arrayOfObjects addObject:@"Object Two"];
[arrayOfObjects addObject:@"Object Three"];
[arrayOfObjects addObject:@"Object Four"];
[arrayOfObjects addObject:@"Object Five"];

Set the seed to the system clock. This will ensure that you get different results every time your run your app.

srandom(time(NULL));

Here is how to get a random number - the number at the end of the statement indicates what the upper limit is. However, the function returns numbers starting with 0 so in practice you will get five results ranging from 0 to 4.

int r = random() % 5;

At this point we have the random number assigned to r and we can use it in any way we like. This is an example of using this number to pick an object our of our array.

NSLog(@"Object = %@", [arrayOfObjects objectAtIndex:r]);

As you can imagine, there are a lot of fun things that you could do with the random function: game logic, random thing of the week and so on.

What would you like to use the random function for in your app?

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 尝到了母爱的滋味400 让儿子尝试了一次中文字 我尝到了母爱的滋味40 我尝到了母爱的滋味400小说下载 好胀胀死妈了乖乖儿子中文字 我尝到了母爱的滋味300 儿子别射J去妈会怀孕视频中文 全屏儿子射J去妈怀孕了漫画 全屏无遮单身妈和儿 四川真实亲妈视频y 全屏无遮单身妈和儿子漫画 全屏无遮单身妈和儿子线播放 青岛重庆真实儿子亲妈 全屏无遮单身在线播放 四川真实亲妈视频链接 全屏无遮单身妈和儿子在线播放中文字 白边液越用白边越大 四川亲妈真实视频 普通话对白边电话边看边干 浙江边干边对白边对白边对白 离婚后一直跟儿子做 边骂脏话对白 离婚多年生理需求和儿子 儿子很帅没忍住和他 离婚后跟儿子做 和儿子一起旅游没忍住 离婚很多年和儿子一起 怀孕了、是儿子的 子母相伦动漫视频 离婚多年和儿子一起打工住一起没忍住 双子母视频 视频播放 与岳 母坐摩托车txt小说 我的丝母韵母txt 经典家庭伦txt丝母韵欲下载 经典家庭伦txt丝母韵欲阅读 经典家庭伦txt丝母韵欲全文阅读 笔趣阁丝母欲韵1-5 我的丝母韵欲txt下载 丝母欲韵1-5阅读 水利局的妈赵丽颖我的丝母欲韵 我的丝母欲韵4-9