How To Use Blocks in iOS 5 Tutorial – Part 1

This is a blog post by iOS Tutorial Team member Adam Burkepile, a full-time Software Consultant and independent iOS developer. Check out his latest app Pocket No Agenda, or follow him on Twitter. Blocks are an incredibly powerful extension to C/Objective-C. They allow you to wrap up chunks of code in self-contained units and pass […] By .

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 2 of this article. Click here to view the first page.

Setting Up IBOutlets and IBActions

Now we need to set up the connection between the user interface we just created and our code. This is where IBOutlets and IBActions come in. The IB part here refers to Interface Builder which is used to create user interfaces in Xcode.

  • An IBOutlet is basically a connection between a user interface element (for instance a label or a button) and the reference to that element in our code.
  • An IBAction is an action (or a method, if you prefer) in our code which can be hooked up to a specific event (tapping a button, for example) in the interface we designed.

So let’s write some code to hook the various UI elements via IBOutlets and IBActions.

Close the Utilities sidebar and open the Assistant editor. Depending on how you have the assistant editor set to display, your screen might (or might not) look like the screenshot below. If you want to change how the Assistant editor is displayed, you can do so via the View – Assistant Editor menu option.

Let’s start with the buttons. Select the “-1” button, hold down the Control key and and drag into the code in the Editor view. This will automate the creation of an IBOutlet for the button.

For this object, all you need to do is name it. I like to prefix all my outlets with “ib” so it makes it easier to find all my outlets in Xcode autocomplete. Name this object “ibRemoveItemButton” and click Connect.

Now do the same for the “+1” button, and name it “ibAddItemButton.”

Next, set up outlets for the red arrow buttons. Name them “ibPreviousItemButton” and “ibNextItemButton.”

Set up an outlet for the total button named “ibTotalOrderButton.”

Now set up outlets for the labels and the image view. From left to right, name them:

  • ibChalkboardLabel
  • ibCurrentItemImageView
  • ibCurrentItemLabel

Your IODViewController.h should now look like this:

@interface IODViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIButton *ibRemoveItemButton;
@property (weak, nonatomic) IBOutlet UIButton *ibAddItemButton;
@property (weak, nonatomic) IBOutlet UIButton *ibPreviousItemButton;
@property (weak, nonatomic) IBOutlet UIButton *ibNextItemButton;
@property (weak, nonatomic) IBOutlet UILabel *ibChalkboardLabel;
@property (weak, nonatomic) IBOutlet UIImageView *ibCurrentItemImageView;
@property (weak, nonatomic) IBOutlet UILabel *ibCurrentItemLabel;
@end

Finally, we are going to add the IBActions for the UIButtons. These are the methods that get called in response to certain events (Touch Up Inside, Touch Up Outside, Touch Cancel, etc). With buttons, most of the time we’re using Touch Up Inside.

Select the “-1” button again. Control-drag over to the .h file again.

Be sure to remember to change the Connection type to Action.

This is an IBAction, so I prefix mine with “iba.” If you want to follow this convention, name this outlet “ibaRemoveItem.” Then click Connect.”

Do the same for the “+1” button, naming the action “ibaAddItem”…

…and for the Red Left Triangle button, naming the action “ibaLoadPreviousItem”…

…and don’t forget the Red Right Triangle button. Call the action “ibaLoadNextItem”:

Finally, add an IBAction for the “Total” button in the lower left, and name it “ibaCalculateTotal.”

Setting Up Web Service

Before you get on to coding, it’s time to set up the web service. I’m not going to explain this in too much detail, as there are already several tutorials on this site that do a good job covering web services (How To Write A Simple PHP/MySQL Web Service for an iOS App and How to Write an iOS App That Uses a Web Service).

The code below shows you what the PHP code for the web service will look like:

<?php  
function getStatusCodeMessage($status) {
    $codes = Array(
        100 => 'Continue', 
        101 => 'Switching Protocols', 
        200 => 'OK', 
        201 => 'Created', 
        202 => 'Accepted', 
        203 => 'Non-Authoritative Information', 
        204 => 'No Content', 
        205 => 'Reset Content', 
        206 => 'Partial Content', 
        300 => 'Multiple Choices', 
        301 => 'Moved Permanently', 
        302 => 'Found', 
        303 => 'See Other', 
        304 => 'Not Modified', 
        305 => 'Use Proxy', 
        306 => '(Unused)', 
        307 => 'Temporary  Redirect', 
        400 => 'Bad Request', 
        401 => 'Unauthorized', 
        402 => 'Payment Required', 
        403 => 'Forbidden', 
        404 => 'Not Found', 
        405 => 'Method Not Allowed', 
        406 => 'Not Acceptable', 
        407 => 'Proxy Authentication Required', 
        408 => 'Request Timeout', 
        409 => 'Conflict', 
        410 => 'Gone', 
        411 => 'Length Required', 
        412 => 'Precondition Failed', 
        413 => 'Request Entity Too Large', 
        414 => 'Request-URI Too Long', 
        415 => 'Unsupported Media Type', 
        416 => 'Requested  Range Not Satisfiable', 
        417 => 'Expectation Failed', 
        500 => 'Internal  Server Error', 
        501 => 'Not Implemented', 
        502 => 'Bad Gateway', 
        503 => 'Service Unavailable', 
        504 => 'Gateway Timeout', 
        505 => 'HTTP Version Not Supported'
    );

    return (isset($codes[$status])) ? $codes[$status] : '';
}

 // Helper method to send a HTTP response code/message
function sendResponse($status = 200, $body = '', $content_type = 'text/html') { 
    $status_header = 'HTTP/1.1 ' . $status . '     ' . getStatusCodeMessage($status);
    header($status_header);
    header('Content-type:     ' . $content_type);
    echo $body;
}

class InventoryAPI {
    function getInventory() {
        $inventory = array(
            array("Name"=>"Hamburger","Price"=>0.99,"Image"=>"food_hamburger.png"),
            array("Name"=>"Cheeseburger","Price"=>1.20,"Image"=>"food_cheeseburger.png"),
            array("Name"=>"Fries","Price"=>0.69,"Image"=>"food_fries.png"),
            array("Name"=>"Onion Rings","Price"=>0.69,"Image"=>"food_onion-rings.png"),
            array("Name"=>"Soda","Price"=>0.75,"Image"=>"food_soda.png"),
            array("Name"=>"Shake","Price"=>1.20,"Image"=>"food_milkshake.png")
        );

        sendResponse(200, json_encode($inventory));
    }
}

sleep(5);

$api = new InventoryAPI;
$api->getInventory();
?>

My web service is a pretty simple PHP script that returns an array that has been JSON encoded. The array contains what’s known as associative arrays under PHP (they’re called dictionaries under Objective-C), that contain the name, price, and image file name for the item.

The only other thing of note in the above code is the sleep(5) statement 3 lines up from the bottom. I’m using this to simulate a slow web service, so as to better show how Blocks can help perform asynchronous operations.

You can copy the above code into a file with the .php extension and host it somewhere or simply use mine at http://adamburkepile.com/inventory/.

Where to Go From Here?

An example project for this part of the tutorial can be downloaded here.

Wow, that was a lot of stuff that had nothing to do with blocks! But now that we’re done setting up the view and web service, we can get down to the fun part in the next installment: coding!

So get yourself over to Part Two, where we will use blocks to make our diner app fully-functional.

Until then, join in the forum discussion below with your questions, comments and suggestions!


This is a blog post by iOS Tutorial Team member Adam Burkepile, a full-time Software Consultant and independent iOS developer. Check out his latest app Pocket No Agenda, or follow him on Twitter.