ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Learn the Objective-C Switch Statement

Updated on January 10, 2013
Source

(c) 2013 kevin languedoc (klanguedoc)

Objective-C, the main programming language for Apple’s OS X and iOS operating systems and platforms, provides constructs for flow control. Flow control is a mechanism that provides programming languages a certain amount of decision making capabilities. Objective-C has two flow control constructs: the switch statement and the if...else...elseif statement. This tutorial will explain the switch statement, its syntax, where and when it is appropriate to use instead of the if...else...elseif statement and also provides examples on the different implementations or function models.

The switch statement in Objective-C is the same as the switch statement in the C programming, so knowing one will naturally allow you, the developer, to use your knowledge with the other language, especially since Objective-C is a superset of the C programming language and C is natively supported. Every programming language has a switch statement as was invented by Stephen Kleene in 1952 and published in his Introduction to Metamethematics. However the switch statement is not implemented in the same way across all languages, there are even variations amongst C based languages.

General Syntax

The switch statement uses a tree/branches design to evaluate numerical values and to return a 1 if the boolean expression being evaluated returns TRUE, otherwise returns -1 is the numerical expression is FALSE, meaning that no branch expression exists that matches the expression under evaluation, at which time, the routine can be directed to the default branch. As each branch expression is evaluated with the expression n, if a match is found, the flow then enters this branch and performs the desired computational and functional requirements and executes the break statement thus halting any further useless evaluations. The code sample below depicts a standard syntactic implementation.

int n = numerical expression to be evaluated
switch(n)
	case value1
		break;
	case value2
		break;
	case value_nth
		break;
	default

Objective-C Syntax and Examples

The switch statement in Objective-C begins with the “switch” keyword and includes an argument as an expression of type int. You can only evaluate a value of the int data type. The switch expressions defined in the branches are enclosed in curly braces. Each expression to be matched begins with the case keyword and finishes with a colon “:”. The Case expression to be evaluated is terminated or demarcated by the break keyword which is followed by the semi-colon “;”. In between are the statements to be executed. If no match can be found, the switch statement evaluation enters the default branch that can contain any number of logical statements to be executed.

switch (expression)

 {
     case equalledValue1:

          statements

          break;

     case equalledValue2:

          statements

          break;

     default:

          statements

          break;

 }

Another way to use the switch statement is to use an enum as follows:

enum label
{
	VALUE1 = 1,
	VALUE2 = 2,
	VALUE3 = 3,

};

switch(label)
{
	case VALUE1:
	//statements to be executed
	break;
case VALUE1:
	//statements to be executed
	break;
case VALUE1:
	//statements to be executed
	break;
default:
};

Test Project

To test the switch statement in a real situation create an iOS Single-View Application project. Open the storyboard and add a button and label and create an IBOutlet for the UILabel and IBAction for the button. To create the IBOutlet and IBAction, open the header file by clicking on the Editor assistant and ctrl+drag a connection from each UIControl, naming each in turn. To create the IBAction, you will need to change the connection type from the IBOutlet default to IBAction. Also add an int variable, enclosed in curly braces, named check. See the header code listing below. This will be used to evaluate the current integer value when the button is clicked.

SwitchIt - ViewController.h

//
//  ViewController.h
//  SwitchIt
//
//  Created by Kevin Languedoc on 1/1/13.
//  Copyright (c) 2013 Kevin Languedoc. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    int check;
}
@property (strong, nonatomic) IBOutlet UILabel *outletTxt;
- (IBAction)actionBtn:(id)sender;

@end

Then close the Editor assistant and open the implementation file by clicking on the file in the project explorer. Locate the IBAction method that was created in the previous step and add the following code in the body:

SwitchIt - IBAction Implementation (ViewController.m)

- (IBAction)actionBtn:(id)sender {
    
    
    switch (check) {
        case 1:
            [self outletTxt].text=@"One was set";
            check ++;
            break;
        case 2:
            [self outletTxt].text=@"Two was set";
            check ++;
            break;
        case 3:
            [self outletTxt].text=@"Three was set";
            check ++;
            break;
        default:
            [self outletTxt].text=[NSString stringWithFormat:@"The number is %d",check];
            check ++;

            break;
    }
}

SwitchIt - Initialize the Check Variable

To initialize the int check variable, set the variable to 0 in the viewDidLoad method so that it gets initialized when the app is first loaded. As the button is click, the check variable gets incremented. When the value exceeds 3 the switch statement falls into the default statement. When the button is first clicked the value of heck is 0 so the switch statement goes to the default since the first case expression is 1.

SwitchIt - viewdidLoad check Initialization

- (void)viewDidLoad
{
    [super viewDidLoad];
	check=0;
}

The switch statement is very effective for long flow control code blocks instead of using if...else...elseif statement. However on the down side you can only evaluate int values. Compile and run the app or play the enclosed video to see the switch statement in action.

The switch statement is a powerful construct for flow management. But it has its limitations like not being able to evaluate non numerical values.

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile image
      Author

      Kevin Languedoc 3 years ago from Canada

      Using strong means that you own and control the property. The compiler won't destroy the object until you decide to do so.

    • profile image

      Pawan Rai 4 years ago

      why you defined a outlet as strong

      "@property (strong, nonatomic) IBOutlet UILabel *outletTxt;"

      any particular reason?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)