ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Objective-C Programming | if...else Logical Expressions

Updated on July 26, 2012
klanguedoc profile image

Kevin is Software Developer with 20 years experience designing and building business intelligence and system integration solutions.

Logical operations in Objective-C are performed using the logical operators from the C language. The most common and practical, the if logical operator, allows an app to make choices using two or more Boolean expressions. The syntax is as follows:

The basic If syntax
The basic If syntax

In the preceding example, if the condition is true then the code immediately following the Boolean statement will be executed. Another version of the above would check to see if the two values to not match by including the exclamation mark, which denotes a negative like this:

Negative Boolean expressions
Negative Boolean expressions

The next form of the if logical operations would include the else condition which would be evaluated if the first if statement was either true or false depending on the intended use:

The if else Boolean operation
The if else Boolean operation

The above version evaluates the Boolean expression. If the evaluation is true, then execute a set of instructions, otherwise the alternate, or false instructions will be executed. The if statement includes curly braces {} to group the code to executed together. The next version will specify many more Boolean operations using the else if conditional argument:

The complex if else if operation
The complex if else if operation

This type of logical operation can have as many Boolean expression as required for the program to work effectively. As with the other logical operations, the program will transfer the execution of the flow based on the positive evaluation of an expression.

To further expand on the basic model, the Boolean expression can involved several Boolean expressions using the || “or” operator or the && “and” operator:

Using the (or) || operator and the && (and) operator
Using the (or) || operator and the && (and) operator

Using the || operator, the first Boolean expression is evaluated. If the expression is true, then the flow stops and the expression is executed. Otherwise the second Boolean expression is evaluated in turn. Alternatively the && “and” can be used:

Combining multiple Boolean expressions with the (and) && operator
Combining multiple Boolean expressions with the (and) && operator

Since the order of preference is always left to right, the order can be changed using parentheses:

Using parentheses to control the order of evaluation
Using parentheses to control the order of evaluation

In the above example, the Boolean expressions 2 and 3 will be evaluated first because they are surrounded by parentheses.

Xcode examples

To actually see how the if conditional operators work and behave, it is best to actually write some code and execute the code. To that end, here are some sample code in Xcode that can be reproduced to try out the if statements yourself.

Example - 1 : Simple if

Create an Xcode Single View project
Name it: Ifs or something else to your liking

Create the project
Create the project

Once created, add a new Objective-C Class
Name: Fruit
In the header file add two NSString instance variables
Name: fruitName
Name: fruitType
Also add the getter and setter properties in the header and implementation files

The Fruit object
The Fruit object

We will use this class to evaluate our if operations

To implement this Fruit class, we will need another class. So create another subclass of type NSObject
Name it: TheIfOperations
Declare the following instance variables and methods:
Name it: displaySomeIfs, return type is void or no return type

In the implementation file, add the following code to the displaySomeIfs.

TheIfOperations header
TheIfOperations header

In the implementation file, add the following code to the displaySomeIfs.

-(void)displaySomeIfs{
    
    
    Fruit *apple = [[Fruit alloc] init];
    apple.fruitName=@"macintosh";
    
    Fruit *orange = [[Fruit alloc] init];
    orange.fruitName = @"navel";
    
    
    if ([apple isEqual:orange]) {
        NSLog(@"These fruits are the same");
    }else{
        NSLog(@"These fruits are not the same");
    }
}

To make this method, also call this method in the kvlAppDelegate implementation file in the didFinishLaunchingWithOptions method:

Call the displaySomeIfs method
Call the displaySomeIfs method

The method creates two Fruit objects and set their fruitName properties. The if statement evaluates the Boolean expression, apple == orange and writes to the Console using the NSLog utility class from the cocoa framework:

Example 2 - Complex if
This example will demonstrate an if else if scenario. We will use the same Fruit class but will add a new method to the TheIfOperations class:
Name: ComplexIf
Return type: void

-(void)ComplexIf{
    Fruit * grape = [[Fruit alloc] init];
    Fruit * lemon = [[Fruit alloc] init];
    Fruit * grapefruit = [[Fruit alloc] init];
    
    grape.fruitType=@"grape";
    lemon.fruitType = @"citrus";
    grapefruit.fruitType = @"citrus";
    
    if([grape.fruitType isEqualToString:lemon.fruitType])
    {
        NSLog(@"grapes and lemons are the same type of fruit.");
        
    }else if([grape.fruitType isEqualToString:grapefruit.fruitType]){
        NSLog(@"Ok, grapes and grapefruits are the same kind of fruit.");
        
    }else if([lemon.fruitType isEqualToString:grapefruit.fruitType]){
        NSLog(@"Ok, these two fruits are both citrus");
        
    }else{
        NSLog(@"none of these fruits are the same.");
    }
    
    
    
}

This method demonstrate how to test for multiple Boolean conditions. If none satisfy any the conditions, the else clause if executed. Finally, the method’s call must be added to the same method in thr kvlAppDelegate method above.

Example 3 - Multiple Boolean Conditions
Define yet another method to evaluate multiple conditions simultaneously. As describe above, this method will show the use of using || or and && logical operators.

Add another method to the TheIfOperations class and add the code as below
Name: multipleConditions
Return type: void

-(void)MultipleConditions{
    Fruit * fruits;
    Fruit * tomatoes;
    Fruit * apples;
    
    
    fruits = [[Fruit alloc] init];
    tomatoes = [[Fruit alloc] init];
    apples = [[Fruit alloc] init];
    
    fruits.fruitType = @"food";
    tomatoes.fruitType = @"food";
    apples.fruitType = @"apple";
    
    if([apples.fruitType isEqualToString:tomatoes.fruitType] && [fruits.fruitType isEqualToString: apples.fruitType])
    {
        NSLog(@"These fruits are the same");
        
    }else if([fruits isFruit:fruits.fruitType :tomatoes.fruitType]){
        NSLog(@"These fruits are the same");
    }else{
        NSLog(@"These fruits are not the same");
    }

}

As the above example demonstrates, you can also use a method with a BOOL return type to evaluate the Boolean expression.

In Summary

The if logical expression can have many forms to suit many types of scenarios. It is a very versatile logical expression.

Fruit.h

//
//  Fruit.h
//  Ifs
//
//  Created by Kevin Languedoc on 1/22/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Fruit : NSObject{
    NSString *fruitName;
    NSString *fruitType;
}

@property(strong,nonatomic)NSString *fruitName;
@property(strong,nonatomic)NSString *fruitType;

-(BOOL)isFruit:(NSString *)fruitOne:(NSString *)fruitTwo;

@end

Fruit.m

//
//  Fruit.m
//  Ifs
//
//  Created by Kevin Languedoc on 1/22/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import "Fruit.h"

@implementation Fruit

@synthesize fruitName = _fruitName;
@synthesize fruitType = _fruitType;

-(BOOL)isFruit:(NSString *)fruitOne:(NSString *)fruitTwo{

    
    if(fruitOne == fruitTwo){
        return TRUE;
    }
    return FALSE;
}

@end

TheIfOperations.h

//
//  TheIfOperations.h
//  Ifs
//
//  Created by Kevin Languedoc on 1/21/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TheIfOperations : NSObject


-(void)displaySomeIfs;

-(void)ComplexIf;

-(void)MultipleConditions;
@end

TheIfOperations.m

//
//  TheIfOperations.m
//  Ifs
//
//  Created by Kevin Languedoc on 1/21/12.
//  Copyright (c) 2012 kCodebook. All rights reserved.
//

#import "TheIfOperations.h"
#import "Fruit.h"

@implementation TheIfOperations


-(void)displaySomeIfs{
    
    
    Fruit *apple = [[Fruit alloc] init];
    apple.fruitName=@"macintosh";
    
    Fruit *orange = [[Fruit alloc] init];
    orange.fruitName = @"navel";
    
    
    if ([apple isEqual:orange]) {
        NSLog(@"These fruits are the same");
    }else{
        NSLog(@"These fruits are not the same");
    }
}


-(void)ComplexIf{
    Fruit * grape = [[Fruit alloc] init];
    Fruit * lemon = [[Fruit alloc] init];
    Fruit * grapefruit = [[Fruit alloc] init];
    
    grape.fruitType=@"grape";
    lemon.fruitType = @"citrus";
    grapefruit.fruitType = @"citrus";
    
    if([grape.fruitType isEqualToString:lemon.fruitType])
    {
        NSLog(@"grapes and lemons are the same type of fruit.");
        
    }else if([grape.fruitType isEqualToString:grapefruit.fruitType]){
        NSLog(@"Ok, grapes and grapefruits are the same kind of fruit.");
        
    }else if([lemon.fruitType isEqualToString:grapefruit.fruitType]){
        NSLog(@"Ok, these two fruits are both citrus");
        
    }else{
        NSLog(@"none of these fruits are the same.");
    }
    
    
    
}

-(void)MultipleConditions{
    Fruit * fruits;
    Fruit * tomatoes;
    Fruit * apples;
    
    
    fruits = [[Fruit alloc] init];
    tomatoes = [[Fruit alloc] init];
    apples = [[Fruit alloc] init];
    
    fruits.fruitType = @"food";
    tomatoes.fruitType = @"food";
    apples.fruitType = @"apple";
    
    if([apples.fruitType isEqualToString:tomatoes.fruitType] && [fruits.fruitType isEqualToString: apples.fruitType])
    {
        NSLog(@"These fruits are the same");
        
    }else if([fruits isFruit:fruits.fruitType :tomatoes.fruitType]){
        NSLog(@"These fruits are the same");
    }else{
        NSLog(@"These fruits are not the same");
    }

}
@end

kvlAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    TheIfOperations *testOne = [[TheIfOperations alloc] init];
   // [testOne displaySomeIfs];
    [testOne ComplexIf];
    return YES;
}

Comments

    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Yes, you are right. This is standard programming practice, no matter the language used. i will change it. Thanks for the feedback

    • profile image

      Steve W 

      6 years ago

      Good introductory article :)

      But using == to test for string equality is a bad habit to get into as they won't always be pointing to the same values.

      Using the NSString -isEqualToString: method is generally a better approach.

      See http://stackoverflow.com/questions/3703554/underst... for a more thorough explantation.

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Thanks. Much appreciated. I think it is important to really grasp the concept first, to zero in on what is important, before moving on to more complex examples or tutorials.

    • profile image

      Wilson 

      6 years ago

      I think that this article is very useful for people that are starting with Objective-C as me. Since I can tell you that is very very easy but at the same time It helps a lot that simplicity when you are learning.

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Thanks. computer programming can be a lot of fun and can also let you be very creative, much like writing and drawing. I hope these tutorials help with you pursuit.

    • Reegan777 profile image

      Reegan777 

      6 years ago from Cut Off, Lousiana

      Very informative, I've been interested on computer programming for some time now and this is a good example of it.

    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)