您的位置:首页 > 移动开发

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

2009-06-10 22:16 951 查看
原文地址: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?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐