ARCRandom in iPhone

Introduction

In this article I will create a Single View application. In this article I will use a Piker view, button and label from outlet and set it on nib. In this app we check the functionality of a random function. In this article we make a combination of two numbers and compare them to a random number that was generated by arcrandom(). If both match then you win otherwise try again.

To understand it we use the following.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now select Single View Application and click on Next.

Step 4

Now provide your Product Name and Company Identifier.

Step 5

Select the location where you want to save your project and click on Create.

Step 6

Now here we write the code.

ViewController.h

#import <UIKit/UIKit.h>
@interface PickerViewController : UIViewController<UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) IBOutlet UILabel *status_lbl;
@property (nonatomic, strong) IBOutlet UIPickerView *valueChange_Picker;
- (IBAction)checkEntry:(UIButton *)sender;
@end

ViewController.m

#import "PickerViewController.h"
@interface PickerViewController ()
@end
@implementation PickerViewController
@synthesize valueChange_Picker, status_lbl;

//PickerView delegate methods

- (
NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return 10;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [NSString stringWithFormat:@"%d", row];
}
//Action methods
- (IBAction)checkEntry:(UIButton *)sender
{
int winningNumber = (arc4random() % 100) ;
int chosenNumber;
int tens = [self.valueChange_Picker selectedRowInComponent:0]*6;
int ones = [self.valueChange_Picker selectedRowInComponent:1];
chosenNumber = tens + ones;if (chosenNumber == winningNumber) {
self.status_lbl.text = @"You Win!";
} else {
self.status_lbl.text = [NSString stringWithFormat:@"Sorry, the winning number was: %d", winningNumber];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.status_lbl.text = @"Choose a number…";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.

}
@end

Step 7

Finally we click on the Run button to show the output.

Step 8

Output 1  in iPhone:

Output1-in-iPhone.png

Output 2 in iPhone

Output2-in-iPhone.png


Similar Articles