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

原文地址: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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值