Recently I have been learning Objective-C through Treehouse tutorials. The tutorials are project based, the first of which is the development of a Crystal Ball iOS app. I have been making steady progress on this app while gradually adding to its capabilities. The Objective-C tutorials feel a bit different, and more enjoyable compared to the C programming tutorials. The project element really adds a sense of accomplishment by seeing additional capabilty being added to the app.
One of the things I learned today was about randomization. The Crystal Ball requires the ability to display random results upon pressing a “Predict” button.
iOS apps with random number capability use algorithms to create this functionality. The numbers are not truly random as they are generated via a mathematical formula, so they are referred to as pseudo-random.
In this case there are ten possible outcomes, laebeled 0 through 9:
0: @”It is certain”
1: @”It is decedidely so”
2: @”All signs point to yes”
3: @”The stars are not aligned”
4: @”My reply is no”
5: @”It is doubtful”
6: @”Better not tell you now”
7: @”Concentrate and ask”
8: @”Unable to answer now”
9: @”Maybe, yes”
The max number is the length of the array, which in out instance is 10. The following formula applies to randomization:
To generate a random number, we use a C function called “arc4random_uniform”, which is actually quite simple. It only requires modifying two lines of code to implement within the Crystal Ball app.
The following steps were used to implement the random number generator within our Objective-C code “ViewController.m” file:
1. Create an “int” local variable named “random” and make it equal to the C function.
int random = arc4random_uniform(self.predictions.count);
2. Refer to “self.predictions.count” which will give us the length of our array:
self.predictionLabel.text = [self.predictions objectAtIndex : random];
Once this is implemented, each time a user clicks on the Predict button it will display one of our random responses. In this instance only the “ViewController.m” file was modified, but I have included the others for completeness. The first is “ViewController.m”:
“ViewController.m” file with implemented code highlighted:
App running in iPhone simulator:
1. Treehouse. iOS Development. Build A Simple iPhone App. Creating A Data Collection. Randomization: http://teamtreehouse.com