The Basics of Objective-C Programming (iOS 5)

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
Testing iOS 5 Apps on the iPad – Developer Certificates and Provisioning ProfilesThe Basics of Object Oriented Programming in Objective-C (iOS 5)

Purchase the fully updated iOS 8/Swift edition of this book in eBook ($14.99) format
iOS 8 App Development Essentials eBook (ePub/PDF/Kindle) edition contains 99 chapters.

Buy eBook

In order to develop iOS apps for the iPad it is necessary to use a programming language called Objective-C. A comprehensive guide to programming in Objective-C is beyond the scope of this book. In fact, if you are unfamiliar with Objective-C programming we strongly recommend that you read a copy of a book called Objective-C 2.0 Essentials. This is the companion book to iPad iOS 5 Development Essentials and will teach you everything you need to know about programming in Objective-C. In the next two chapters we will take some time to go over the fundamentals of Objective-C programming with the goal of providing enough information to get you started.


[edit] Objective-C Data Types and Variables

One of the fundamentals of any program involves data, and programming languages such as Objective-C define a set of data types that allow us to work with data in a format we understand when writing a computer program. For example, if we want to store a number in an Objective-C program we could do so with syntax similar to the following:

int mynumber = 10;

In the above example, we have created a variable named mynumber of data type integer by using the keyword int. We then assigned the value of 10 to this variable. Objective-C supports a variety of data types including int, char, float, double, boolean (BOOL) and a special general purpose data type named id.

Data type qualifiers are also supported in the form of long, long long, short, unsigned and signed. For example if we want to be able to store an extremely large number in our mynumber declaration we can qualify it as follows:

long long int mynumber =  345730489;

A variable may be declared as constant (i.e. the value assigned to the variable cannot be changed subsequent to the initial assignment) through the use of the const qualifier: const char myconst = ‘c’;

[edit] Objective-C Expressions

Now that we have looked at variables and data types we need to look at how we work with this data in an application. The primary method for working with data is in the form of expressions.

The most basic expression consists of an operator, two operands and an assignment. The following is an example of an expression:

int myresult = 1 + 2;

In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable named myresult. The operands could just have easily been variables (or a mixture of constants and variables) instead of the actual numerical values used in the example.

In the above example we looked at the addition operator. Objective-C also supports the following arithmetic operators:

-(unary)Negates the value of a variable or expression

Another useful type of operator is the compound assignment operator. This allows an operation and assignment to be performed with a single operator. For example one might write an expression as follows:

x = x + y;

The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator:

x += y

Objective-C supports the following compound assignment operators:

x += yAdd x to y and place result in x
x -= ySubtract y from x and place result in x
x *= yMultiply x by y and place result in x
x /= yDivide x by y and place result in x
x %= yPerform Modulo on x and y and place result in x
x &= yAssign to x the result of logical AND operation on x and y
x |= yAssign to x the result of logical OR operation on x and y
x ^= yAssign to x the result of logical Exclusive OR on x and y

Another useful shortcut can be achieved using the Objective-C increment and decrement operators (also referred to as unary operators because they operate on a single operand). As with the compound assignment operators described in the previous section, consider the following Objective-C code fragment:

x = x + 1; // Increase value of variable x by 1
x = x - 1; // Decrease value of variable x by 1

These expressions increment and decrement the value of x by 1. Instead of using this approach it is quicker to use the ++ and -- operators. The following examples perform exactly the same tasks as the examples above:

x++; Increment x by 1
x--; Decrement x by 1

These operators can be placed either before or after the variable name. If the operator is placed before the variable name the increment or decrement is performed before any other operations are performed on the variable.

In addition to mathematical and assignment operators, Objective-C also includes a set of logical operators useful for performing comparisons. These operators all return a Boolean (BOOL) true (1) or false (0) result depending on the result of the comparison. These operators are binary operators in that they work with two operands.

Comparison operators are most frequently used in constructing program flow control logic. For example an if statement may be constructed based on whether one value matches another:

if (x == y)
      // Perform task

The result of a comparison may also be stored in a BOOL variable. For example, the following code will result in a true (1) value being stored in the variable result: BOOL result;

int x = 10;
int y = 20;

result = x < y;

Clearly 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of Objective-C comparison operators:

x == yReturns true if x is equal to y
x > yReturns true if x is greater than y
x >= yReturns true if x is greater than or equal to y
x < yReturns true if x is less than y
x <= yReturns true if x is less than or equal to y
x != yReturns true if x is not equal to y

Objective-C also provides a set of so called logical operators designed to return boolean true and false. In practice true equates to 1 and false equates to 0. These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^).

The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently 1 (true), prefixing the variable with a '!' character will invert the value to 0 (false):

bool flag = true; //variable is true
bool secondFlag;
secondFlag = !flag; // secondFlag set to false

The OR (||) operator returns 1 if one of its two operands evaluates to true, otherwise it returns 0. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true:

if ((10 < 20) || (20 < 10))
        NSLog (@"Expression is true");

The AND (&&) operator returns 1 only if both operands evaluate to be true. The following example will return 0 because only one of the two operand expressions evaluates to true:

</pre> if ((10 < 20) && (20 < 10))

     NSLog (@"Expression is true");


The XOR (^) operator returns 1 if one and only one of the two operands evaluates to true. For example, the following example will return 1 since only one operator evaluates to be true:

if ((10 < 20) ^ (20 < 10))
      NSLog("Expression is true");

If both operands evaluated to true or both were false the expression would return false. Objective-C uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator (also known as the conditional operator) is as follows:

[condition] ? [true expression] : [false expression]

The way this works is that [condition] is replaced with an expression that will return either true (1) or false (0). If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action:

int x = 10;
int y = 20;
NSLog(@"Largest number is %i", x > y ? x : y );

The above code example will evaluate whether x is greater than y. Clearly this will evaluate to false resulting in y being returned to the NSLog call for display to the user:

2009-10-07 11:14:06.756 t[5724] Largest number is 20

[edit] Objective-C Flow Control with if and else

Since programming is largely an exercise in applying logic, much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed and, conversely, which code gets by-passed when the program is executing. This is often referred to as flow control since it controls the flow of program execution.

The if statement is perhaps the most basic of flow control options available to the Objective-C programmer.

The basic syntax of the Objective-C if statement is as follows:

if (boolean expression) { 
// Objective-C code to be performed when expression evaluates to true 

Note that the braces ({}) are only required if more than one line of code is executed after the if expression. If only one line of code is listed under the if the braces are optional. For example, the following is valid code:

int x = 10;
if (x > 10)
       x = 10;

The next variation of the if statement allows us to also specify some code to perform if the expression in the if statement evaluates to false. The syntax for this construct is as follows:

if (boolean expression) { 
// Code to be executed if expression is true 
} else { 
// Code to be executed if expression is false 

Using the above syntax, we can now extend our previous example to display a different message if the comparison expression evaluates to be false:

int x = 10;
if ( x > 9 )
         NSLog (@"x is greater than 9!");
} else {
         NSLog (@"x is less than 9!");

In this case, the second NSLog statement would execute if the value of x was less than 9.

So far we have looked at if statements which make decisions based on the result of a single logical expression. Sometimes it becomes necessary to make decisions based on a number of different criteria. For this purpose we can use the if ... else if ... construct, the syntax for which is as follows:

int x = 9;
if (x == 10)
       NSLog (@"x is 10");
else if (x == 9)
       NSLog (@"x is 9");
else if (x == 8)
         NSLog (@"x is 8");

[edit] Looping with the for Statement

The syntax of an Objective-C for loop is as follows:

for ( ''initializer''; ''conditional expression''; ''loop expression'' )
      // statements to be executed

The initializer typically initializes a counter variable. Traditionally the variable name i is used for this purpose, though any valid variable name will do. For example:

i = 0;

This sets the counter to be the variable i and sets it to zero. Note that the current widely used Objective-C standard (c89) requires that this variable be declared prior to its use in the for loop. For example:

int i=0;
for (i = 0; i < 100; i++)
     // Statements here

The next standard (c99) allows the variable to be declared and initialized in the for loop as follows:

for (int i=0; i<100; i++)
    //Statements here

It is possible to break out of a for loop before the designated number of iterations have been completed using the break; statement.

[edit] Objective-C Looping with do and while

The Objective-C for loop described previously works well when you know in advance how many times a particular task needs to be repeated in a program. There will, however, be instances where code needs to be repeated until a certain condition is met, with no way of knowing in advance how many repetitions are going to be needed to meet that criteria. To address this need, Objective-C provides the while loop.

The while loop syntax is defined follows:

while (''condition'')
      // Objective-C statements go here

[edit] Objective-C do ... while loops

It is often helpful to think of the do ... while loop as an inverted while loop. The while loop evaluates an expression before executing the code contained in the body of the loop. If the expression evaluates to false on the first check then the code is not executed. The do ... while loop, on the other hand, is provided for situations where you know that the code contained in the body of the loop will always need to be executed at least once.

The syntax of the do ... while loop is as follows:

       // Objective-C statements here
} while (''conditional expression'')

[edit] Summary

In this chapter we have covered the basic data types, constructs and flow control logic that comprise the Objective-C programming language.

Purchase the fully updated iOS 8/Swift edition of this book in eBook ($14.99) format
iOS 8 App Development Essentials eBook (ePub/PDF/Kindle) edition contains 99 chapters.

Buy eBook

PreviousTable of ContentsNext
Testing iOS 5 Apps on the iPad – Developer Certificates and Provisioning ProfilesThe Basics of Object Oriented Programming in Objective-C (iOS 5)
Personal tools

Find us on Facebook