Getting Started with iOS

This is a “Hello World” tutorial to iOS programming.  We are going to build an iPhone app that has a counter and two buttons.  Tapping the “+1” button increments the counter and tapping “-1” decrements the counter.
Open Xcode and start a new project File->New->Project.  Under iOS templates select Application and then “Single View Application”
Click on “Next” and choose the options for the project.  Type in “Counter” for Product Name and Class Prefix.  Company Identifier can be anything, so put your company name or n/a.  Select iPhone for Device Family.

Click Next to save your new project.  Xcode should have created 5 different files for you:
1) CounterAppDelegate.h
2) CounterAppDelegate.m
3) MainStoryboard.storyboard
4) CounterViewController.h
5) CounterViewController.m

We will make changes to the the last 3 files in this project.

Open MainStoryboard.storyboard.

In the lower right corner is the Object Library.  From the Object Library drag two “Buttons” and a “Label” to the canvas.  Double click on the buttons and on the label and change their titles to the following.

Now we need to create outlets and actions to connect our buttons to the code.  There are a few different ways to create actions and outlets in Xcode.  The easiest one is to click on the assistance editor button.

This will open CounterViewController.h to the right of the storyboard.  Click ctrl and drag from each button to the area between @property and @end in the CounterViewController.h file.  A pop up will appear, select Connection=action and set Name=decrement for the “-1” button and Name=increment for “+1” button.  Press Connect to create the action.

Do the same for the label but set Connection=outlet and Name=label.  We also need to add a counter to keep track of our value.  Again in CounterViewController.h under @interface add the following code “@property (nonatomic) int counter;”  After adding all this CounterViewController.h should look like similar to this.

@interface CounterViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *label;
@property int counter;
- (IBAction)increment:(id)sender;
- (IBAction)decrement:(id)sender;


Open CounterViewController.m find the decrement and increment methods and implement them. They should look like the following when done.

- (IBAction)decrement:(id)sender {
    self.counter -= 1;
    [self.label setText:[NSString stringWithFormat:@"%d", self.counter]];
- (IBAction)increment:(id)sender {
    self.counter += 1;
    [self.label setText:[NSString stringWithFormat:@"%d", self.counter]];

The app is ready to run. Go to Product->Run and wait for the sumulator to load. Every time you press +1 button the number in the label increases by 1, pressing -1 button decreases the counter by 1.