Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (24.65 MB, 900 trang )
As long as the condition is a value other than zero/nil/NULL, the code
inside the if statement will run.
An if statement that has an "otherwise" clause in it is known as if-else-statement, and
it's format is:
if (
/* Your code to get executed if the
} else {
/* Code to get executed if
}
The else clause of the if-else-statement can also contain it's own if statement! That
might sound strange, but consider this scenario. In real life, you can say something
similar to this: "I will go get a cup of coffee, if the place is open, I will get a tall latte, if
it's closed and the other place is open, I will get a cappuccino, otherwise, I will just
come back home and make tea for myself". The part where we said "...if it's closed and
the other place is open..." is an else statement with an if statement embedded in it. Here
is how you would implement that in Objective-C:
if (Coffee place A is open){
Get a Tall Latte from coffee place A
} else if (Coffee place B is open){
Get a Cappuccino from coffee place B
} else {
Come back home and make tea
}
The condition for an if statement, regardless of whether it is a standalone if statement
(like the first condition in the last example) or embedded inside an else-statement, must
resolve to a boolean value. A boolean value is either YES or NO. For instance, the following
code will always get executed, regardless of which condition/device you run it on:
if (YES){
/* This code will get executed whenever the app gets to it */
} else {
/* The app will NEVER get here */
}
The reason behind this is that the condition for the if statement in this example is always
met as long as the YES is the condition. To make things more exciting, you can do
comparisons in the condition supplied to an if statement, like so:
NSInteger integer1 = 123;
NSInteger integer2 = 456;
if (integer1 == integer2){
NSLog(@"Integers are equal.");
} else {
NSLog(@"Integers are not equal.");
}
30 | Chapter 1: The Basics
www.it-ebooks.info
We use the double-equal sign in a conditional because the result of a
double-equal is a boolean value, whereas the single-equal sign might
confuse the compiler and usually returns the value/object on the left
side of the equal sign. It is best to avoid using single-equal signs in a
conditional like an if statement. Instead, compare your values using
double-equal signs.
If you are comparing objects, it is best to use the isEqual: instance method of the
NSObject class:
NSObject *object1 = [[NSObject alloc] init];
NSObject *object2 = object1;
if ([object1 isEqual:object2]){
NSLog(@"Both objects are equal.");
} else {
NSLog(@"Objects are not equal.");
}
For now you don't have to worry about what objects are. This will be
explained in detail in other recipes in this chapter.
Some objects, such as strings, however have their own comparison methods, changing
the way we compare two strings. For instance, you can have two string objects that
contain the same characters. If you compare them using their isEqual: instance method, you will get the result NO, because they are different objects. However, they might
still contain the exact same characters. Because of this, different classes expose their
own comparison methods in Objective-C. For more information about classes, please
refer to Recipe 1.11. To learn more about objects, refer to Recipe 1.14.
An if statement and its else statement can be written with or without curly braces. Using
the former syntax (with curly brackets), you can execute multiple lines of code after
the condition is satisfied. However, without curly brackets, you can write only one line
of code for each condition. Here is an example of the latter syntax without curly braces:
NSString *shortString = @"Hello!";
if ([shortString length] == 0)
NSLog(@"This is an empty string");
else
NSLog(@"This is not an empty string.");
1.8 Comparing Values in Objective-C with an If Statement | 31
www.it-ebooks.info
Be extra careful with logging and if statements without curly-brackets.
Often, when a product goes to production, a production manager might
attempt to comment out all your NSLog methods simply by replacing all
occurrences of NSLog with //NSLog. If you have if statements without
curly brackets, as in our last example, the production manager's commented-out code will look like this:
NSString *shortString = @"Hello!";
if ([shortString length] == 0)
//NSLog(@"This is an empty string");
else
//NSLog(@"This is not an empty string.");
This will break the code and people in the company will not be happy.
It doesn't matter whether they are not happy at you or not happy at the
production manager. That would be a team effort gone wrong, so you
will all be to blame. To avoid this, make sure that you always write your
if statements with curly braces.
See Also
XXX
1.9 Implementing Loops with For Statements
Problem
You want to implement a code that repeats a certain number of times, perhaps applying
the same procedure to every element in an array or some other changing values.
Solution
Use the for statement. The format of this statement is:
for (
}
All three clauses of the for loop are optional. In other words, you can
have a for loop that looks like this:
for (;;){ YOUR CODE HERE }
This is known as an infinite-loop or a loop that has no condition to
terminate and will run forever. This is a very bad programming practice
indeed and you should avoid using it by all means.
32 | Chapter 1: The Basics
www.it-ebooks.info
Discussion
Loops are useful in programming because you will often need to start a loop from one
place to another, from one index to another, or from start to stop. For instance, you
might want to loop through all characters inside a string and count how many "A"
characters you can find in it. Another example is a loop that finds all files in a directory.
This is a loop that finds the number of files and then starts from the first one until it
gets to the last one.
Usually, programmers require a counter in their loops. For instance, you might want
to read all the characters inside a C-String. For this, you will need the index of each
character. If your string is 10 characters long, you will need to go from index 0 to 9. If
your string is 20 characters long, you have to read from index 0 to 19. Since the length
of your string is a variable, you can put it as the exit-conditional of your loop. Here is
an example:
char *myString = "This is my string";
NSUInteger counter = 0;
for (counter = 0;
/* Start from index 0 */
counter < strlen(myString); /* Exit loop when we reach last character */
counter++){ /* Increment the index in every iteration */
char character = myString[counter];
NSLog(@"%c", character);
}
The code that gets executed before the loop (as noted in the Solution section of this
recipe) is obviously optional. In fact, all three main parts of a for loop are optional, but
it is recommended that you think about how you intend to use your loops and use the
three main parts of the for statement accordingly.
Let's have a look at where you would want to skip the first statement of your for loop.
As you could see in the previous section, our counter variable was set to 0 before we
even started our loop. However, we are setting it to 0 again once our loop is about to
start. This is unnecessary in this example, but there is nothing wrong with that approach. If you feel you don't need the redundant code, simply remove it:
char *myString = "This is my string";
NSUInteger counter = 0;
for (; /* empty section */
counter < strlen(myString); /* Exit loop when we reach last character */
counter++){ /* Increment the index in every iteration */
char character = myString[counter];
NSLog(@"%c", character);
}
1.9 Implementing Loops with For Statements | 33
www.it-ebooks.info