Extension 6: Incrementation

In the last Lesson, I used the following expression on Line 11 of the first example:

`n = n + 1`

This is perfectly valid code. The associativity of the equals operator (=) is right-to-left—this means that whatever is on the right of the operator is evaluated first, then the result is assigned back to the variable or identifier on the left side. So in this case, the program first determines the value of n + 1, and assigns this new value back to n. This method is fine, but there are more elegant solutions.

Operator-Equals

The following is completely equivalent to the above example:

`n += 1;`

What this is saying is to evaluate the result of n + 1 and assign it back to n—the identical meaning to the above example. The difference is that in this case the code is clearer, and much more concise. The following are all valid:

```n += 3;    // Same as n = n + 3;
n -= 3;    // Same as n = n - 3;
n *= 3;    // Same as n = n * 3;
n /= 3;    // Same as n = n / 3;
n %=3;     // Same as n = n % 3;```

In each case, the value of n operator 1 is evaluated, then the result is assigned back to n. This construct is highly recommended, and is used almost exclusively in place of the original.

++ and ––

That should be two minus signs; WordPress is over-optimizing the typography.

Returning to the concept of loops, most loops execute a specific number of times; this number is often determined by an upper limit value, and a counter is used to keep track of the increments until the maximum is reached. In these cases, the counter would be incremented by 1. In the original example, the code to do this was

`n = n + 1;`

As described above, n += 1; is also valid.

But incrementing (or decrementing) by 1 is such a popular thing to do in code (believe it or not) that Objective-C (and plain C) has a special construct to do just that:

```n++;     // Increment by 1
n--;     // Decrement by 1 ```

As with the above construct, the double-plus or double-minus is used almost exclusively when the program needs to increment or decrement by 1. At the very least, it saves you typing; at best, compilers can produce more concise and efficient code when the double-plus or double-minus is used (Prata, C Primer Plus, 5th Edition, SAMS: Page 146). Note that these operators increment by exactly 1, and can only be used with integers.

One thing to note is that the increment and decrement operators have a prefix and postfix version.

Prefix versus Postfix

Compare the following statements:

```int n = 4;
if (n++ < 5)     // Case 1
NSLog(@"n is %d", n);
n = 4;           // "Reset" value of n
if (++n < 5)     // Case 2
NSLog(@"n is %d", n);
NSLog(@"n is %d", n);     ```

The output is:

```n is 5
n is 5 ```

There are three NSLogs in the code, yet only two lines of output. This reflects a subtlety in the increment/decrement operators. Why does this happen?

In Case 1, the value of n is compared with 5 first, and then incremented. n was initially set to 4; 4 is less than 5, so the initial NSLog executes. However, by that point, n had been incremented to 5.

In Case 2, the value of n is first incremented, then compared to 5. So n first becomes 5; 5 is not less than 5, and so the second NSLog does not execute. However, the final NSLog displays the value of n, which is now 5.

In the majority of cases, where only the end result is concerned, using the prefix or postfix does not matter—in either case, the end result is 5. However, for intermediate cases, such as the code within the if() statements, the choice does matter.

Finally, happy holidays to all my readers! Thanks for stopping by, and I hope you’ll come back for more. We’ll be getting into the good stuff (objects and more advanced programs) soon—probably before 2011 rolls around. Merry Hanukkah (and Kwanzaa, and whatever else is politically correct)! 😀

Extension 5: The switch Statement

The switch() statement is used in place of a chain of if()else if()else if()else if()else construct, where such a chain does not lead to very readable, follow-able code. The switch() statement is designed for this situation. Here is the general format:

```switch(expression or variable)
{
case value1:
// Program statement
// Program statement
...
break;
case value2:
// Program statement
// Program statement
...
break;
case value3:
// Program statement
// Program statement
...
break;
...
case valueN:
// Program statement
// Program statement
...
break;
default:
// Program statement
// Program statement
...
break;
}```

The expression value in the parentheses at the beginning of the statement is compared to each of the values, and when one of them matches, the following code (note the colon, and the lack of braces around each case), the code below is executed. It then breaks out of the rest of the switch, to avoid executing the rest of it (“overflowing” into the code for the next condition). This can sometimes be used intentionally, but for most of the time make sure to use the break; statement.

If none of the conditions match (the else of an if()else block), the code under the default condition is executed.

The following is an example of a switch() statement and the equivalent if()else block:

```// This is an example of a switch statement.
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString *operator = [[NSString alloc] init];     // We will talk in depth about NSString later on down the road.
// Assume operator has been initialized to a valid value
// Valid values for operator are @"+", @"-", @"*", and @"/"

switch (operator) {
case @"+":
break;
case @"-":
NSLog(@"Operator is for subtraction.");
break;
case @"*":
NSLog(@"Operator is for multiplication.");
break;
case @"/":
NSLog(@"Operator is for division.");
break;
default:
NSLog(@"Unknown operator.");
break;
}

[pool drain];
return 0;
}
```

This code should be rather self-explanatory; operator is compared to the values after each case, and if one of them matches, the executes the corresponding NSLog and breaks out of the switch. If none of them match, then it hits the default statement.

The equivalent if()else block follows:

```// This is an example of a switch statement.
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString *operator = [[NSString alloc] init];
// Assume operator has been initialized to a valid value
// Valid values for operator are @"+", @"-", @"*", and @"/"

/* Note that NSString actually has a comparison method, and that
this method of comparison is not guaranteed to work. We are
overlooking that at the moment for the sake of education. */
if (operator == @"+")
else if (operator == @"-")
NSLog(@"Operator is for subtraction.");
else if (operator == @"*")
NSLog(@"Operator is for multiplication.");
else if (operator == @"/")
NSLog(@"Operator is for division.");
else
NSLog(@"Unknown operator.");    [pool drain];
return 0;
}
```

This code does the same thing as the switch statement above (bar the comment in bold).

The switch() statement is makes more logical sense, but some people find it annoying. It all comes down to a matter of personal preference. No big deal.

BTW less than a month after the previous milestone we are at 2000 views! Thanks to everyone who stopped by, and I hope to see you back!

Postscript: Wikipedia has a nice article on controlling program flow. It is a bit dense, but for anyone who is interested, go check it out! And while you’re there, you might as well see the article on the switch statement as well.

Objective-C Lesson 4: if() statements and Booleans

As mentioned before, boolean values are simply true-or-false. In Objective-C, unlike many other languages, they are represented as YES or NO:

```BOOL trueOrFalse = YES;
BOOL gameOver = NO;
```

Internally, however, they are stored as zero and one.

if() Statements

The if() statement is used to check for conditions. Just like we use if in normal English, if() in code is used to test for a condition—they test for the value of a boolean (or any int—in this case, a zero is considered false; any non-zero value is true).

Here is a simple example of booleans:

```#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

BOOL trueOrFalse = YES;
if (trueOrFalse)
NSLog(@"trueOrFalse is true.");
if (1)
NSLog(@"1 is considered to be true.");
[pool drain];
return 0;
}
```

The output is:

```trueOrFalse is true.
1 is considered to be true.
```

Simple enough, and quite logical.

Obviously, if the condition was false, the statements following would not be executed. The following example demonstrates:

```#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

BOOL trueOrFalse = YES;
if (trueOrFalse)
NSLog(@"trueOrFalse is true.");
if (1)
NSLog(@"1 is considered to be true.");	// If false, statement following is not executed
trueOrFalse = NO;
if (trueOrFalse)
NSLog(@"I lied. trueOrFalse is not true.");
if (0)
NSLog(@"This line should not appear.");
[pool drain];
return 0;
}
```

Unsurprisingly, the results are the same as above.

One important point to make here: if you only have one statement after the if(), you can just leave it like it is above. But if you have more than one statement after the if(), you must enclose them within braces:

```if (trueOrFalse) {
NSLog(@"trueOrFalse is true.");
NSLog(@"This second line must be within the braces.");
}
```

Otherwise, the second (or additional) statements will be executed, regardless of if the condition was true or not.

Extending the if() Statement

In real life though, there are often alternatives: if something is true, do “action1“; else, do “action2“. Objective-C lets you model that quite simply:

```trueOrFalse = YES;
if (trueOrFalse == YES)          // The double-equals sign is a comparison; versus a single equals, which is an assignment. More on this in the next Extension.
NSLog(@"If true, print this");     // This gets printed
else
NSLog(@"Else, print this");        // This does not get printed
trueOrFalse = NO;
if (trueOrFalse)
NSLog(@"If true, print this");    // This does not get printed
else
NSLog(@"Else, print this");       // This gets printed
```

Output is:

```If true, print this
Else, print this
```

This makes logical sense.

You can also extend this by using else if(). This is easier to explain with code:

```int value = 5;
if (value > 0)
NSLog(@"value is greater than zero.");
else if (value == 0)
NSLog(@"value is equal to zero.");
else
NSLog(@"value is less than zero.");
```

Output is:

`value is greater than zero.`

You can have as many else if()s as you want; they simply follow each other:

```int value = 5;
if (value == 6)
NSLog(@"value is equal to 6.");
else if (value == 0)
NSLog(@"value is equal to 0.");
else if (value == 2)
NSLog(@"value is equal to 2.");
else if (value == 10)
NSLog(@"value is equal to 10.");
else
NSLog(@"value does not equal 6, 0, 2, or 10");     // This line is the output.
```

Pitfalls

There are a few issues that may arise with if()statements.

• Forgetting braces: If you have more than one statement that you want to execute given a certain condition, you must enclose them within curly braces.
• Using too many instances of if(): If you want to have a collection of related paths (if…else if…else), you must remember to use else if(). Using a chain of if()s is a completely different thing, logically. Think about it.
• Forgetting the last else: The final else is a “catchall” statement that is executed if none of the previous if() or else if() statements are true. Don’t forget the else; otherwise, you may never get any output. For example, in the last code example, the last else statement was needed; otherwise, it might have appeared that the code was broken.

Conclusion

As you can see, the if() statement is quite simple, but very powerful—it defines “paths” down which your code can travel, based on the value of a condition. In the next Extension, we will be looking at what these conditions can be.

Objective-C Lesson 3: Object-Oriented Programming

When object-oriented programming arrived in the programming world, it was considered a savior of software by some and yet another foolish experiment by others. Regardless of the perspective, we need to define some basic concepts and terminology before we begin

A Thing

An object is a thing. In the real world, you have “things,” all of which have certain properties. For example, you probably have a car—a “thing.” The car has properties, such as paint color, total mileage, make, model, and year. You can also do things with the car, or have something done to it—for example, you can drive twenty miles in the car, or wash the car.

In an object-oriented program, your specific car is an instance of a class, generally called Car. A class is the definition of the object, and in most cases can be thought of as a “factory” for its instances. A class can create many instances of the same type of object, although they have to have different names. An object is simply a variable, but it can be (and usually is) of a custom type.

Instance Variables and Methods

As mentioned before, your car, and any other car, has certain properties that are potentially unique to that specific instance. These properties are known as instance variables, or ivars for short. Instance variables are variables, of either the standard data types, or of any other object, but they are private to the object—that is, every single instance of Car has its own identical set of instance variables; although the variables may be of the same type and number, they can (and usually do) contain different values across different instances.

A method is the proper term for a function, or simply a piece of code that is called upon to perform some action. In Objective-C, there are two types of methods—class methods and instance methods. Class methods are performed directly on the class that an object belongs to—for example, a class methods might ask the car factory how many cars it produced the previous year. Instance methods are performed on specific instances of a class—for example, you might ask one specific car to drive twenty miles, or you might wash one specific car; you wouldn’t do those things to the entire factory. Instance methods affect the state or condition of the object. Just like two identical cars adopt different characteristics over their lifetime, different instances of Car can take on different traits as well.

Message Objects

In Objective-C, there is a specific syntax for calling methods:

[ClassOrInstance method];

The method call begins with an open bracket. This is followed by the name of the class or instance, depending on whether the method belongs to a class or instance. This is followed by a space, and then the name of the method. This is followed by a closing bracket, and the all-important semicolon.
In more formal terminology, the following message call might be described as

The meaning is the same.

Sample Program

Now, with the theory cleared up, we can move on to our first program involving classes.

Program 3.1

```// A simple implementation of a Fraction
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

int numerator = 2;
int denominator = 5;
NSLog(@"This is a fraction with a value of %d/%d", numerator, denominator);

[pool drain];
return 0;
}
```

The output is

`This is a fraction with a value of 2/5`

In Program 3.1, we defined a numerator and denominator variable, and set them to integer values. We then printed the result of this simple fraction.

This program is short and condensed, and seems to be pretty simple—and it is. But what if we had a hundred fractions that we wanted to store? We’d have to keep track of two hundred variables. And performing operations on those variables would not be any easier.

As a matter of fact, Program 3.1 is not a true object-oriented program. It is still written using C-style code. We have not created any objects in the code; our Fraction object still exists only psychologically.

Program 3.2 presents the exact same functionality, except that we actually define this object in code. We then refer to the object as Fraction throughout the program. Don’t worry if it looks daunting; an explanation follows.

Program 3.2

```// A Fraction class
#import <Foundation/Foundation.h>

//———————— Interface ————————

@interface Fraction : NSObject
{
int numerator;
int denominator;
}

- (void)showResults;
- (void)setNumerator:(int)n;
- (void)setDenominator:(int)d;

@end

//———————— Implementation ————————

@implementation Fraction

- (void)showResults {
NSLog(@"This is a fraction with a value of %d/%d", numerator, denominator);
}

- (void)setNumerator:(int)n {
numerator = n;
}

- (void)setDenominator:(int)d {
denominator = d;
}

@end

//———————— Main Program ————————

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// Create an instance of Fraction
Fraction *myFraction;

myFraction = [[Fraction alloc] init];

// Set myFraction to 2/5
[myFraction setNumerator:2];
[myFraction setDenominator:5];

// Display the value of myFraction
[myFraction showResults];

// Clear up memory
[myFraction release];

[pool drain];
return 0;
}
```

The output is

`This is a fraction with a value of 2/5`

Code, Demystified

Program 3.2 is divided into three logical sections. These are known as the interface, implementation, and program section, respectively.

The interface section (delineated by @interface in the code) provides basic program-wide definitions, the implementation section (delineated by @implementation) provides the implementation of the methods, and the program section contains the main code that does something.

The @interface Section

Every class in Objective-C has a single parent, or superclass, from which the class inherits. Next, you have to declare the instance variables that belong to the class. Finally, you declare the methods, or actions, that the class can perform. This is all done in the @interface section, which looks like this:

```@interface ClassName : ParentClassName
{
instanceVariableDeclarations;
}
methodDeclarations
@end
```

Remember that the compiler ignores spaces, so you may put line breaks and spaces anywhere within the code above.
By convention, the name of a class begins with a capital letter, as in the Fraction class.

You can tell that our Fraction class is a subclass of NSObject, which is the root object that almost everything else inherits from, directly or indirectly. NSObject is declared in the Foundation files which you imported.

Fraction contains two instance variables; both are ints. They are called instance variables because every instance of Fraction creates a new set of these variables, unique to that specific instance. So, FractionA’s numerator is a different variable than FractionB’s numerator. Objective-C automatically keeps track of this for you.

Currently, our Fraction class declares (and later implements) three methods. All are instance methods, as noted by the minus sign () preceding each method name. A class method is delineated by a plus sign (+).

Before we discuss the method declaration, we must remember than an object is considered a “black box.” Ideally, objects encapsulate, or hide, their instance variables, from anything except itself. The object exists as a single entity, and anything that works with the object does not need to know, and should not know, about the object’s inner workings. Therefore, we need to declare specific methods to set the variables, because the program should not directly manipulate them. We also need a separate method to print the values, because, once again, the program should not be able to directly access the variables. This is a fundamental concept in Objective-C, and is observed throughout the libraries and code.

The Fraction class defines three methods, all of which return nothing. The value in parentheses before the method name specifies the return type of the method. void is programming parlance for “nothing,” or nil. Any data type or object can be a return value; a method might return a float, int, or another Fraction, as illustrated by the following methods:

```- (int)numerator;
- (float)divide;
- (Fraction *)randomFraction;
```

The asterisk after the Fraction is used to delineate a pointer; this is not an important concept at the moment. For now, simply remember that anytime you create an instance of a custom object, the name of the instance should be prefixed with an asterisk.

All of these methods must return a value somewhere in the method. Just as main returns 0 at the end, these methods must return an int value, a float value, and another instance of Fraction, respectively. The compiler will complain if you do not return a value.

The latter two methods declared in Fraction return no value, but they do each take an integer value as an argument. In the case of setNumerator:, the name of the argument is n. This name is arbitrary, as long as it follows the standard naming conventions, and is used only within the method to refer to the argument. The argument itself exists only within the method; you cannot access n anywhere else in Fraction.

Arguments are values that are passed into a method, which the method would not be able to obtain otherwise. For example, setNumerator: requires a value to set to the numerator, but it would not receive a custom value without an argument.

Note the syntax of these method declarations. The method name begins with the minus or plus, signifying the method type. This is followed by the return type in parentheses, the name of the method, and a colon. This colon is followed by an argument type in parentheses, a name for the argument, and a semicolon. In a method that takes an argument, the colon is considered part of the method name.

A method can take multiple arguments; they are delineated by a space, a new section of the method name, another colon, an argument type, and name. This will be covered in a later chapter.

The @implementation Section

In the implementation section, you define the code that each method implements. The general appearance of the @implementation section is similar to this:

```@implementation ClassName
methodDefinitions;
@end
```

In the implementation of Fraction, you also declare the method types and names, followed by an open brace. Between the opening and closing brace, you insert the code that the method will execute when it is called.

The program Section

In this program, the main program section contains the all-important main function that is the first thing to be executed.

In Program 3.2, we first create an instance of Fraction:

` Fraction *myFraction;`

Again, don’t worry about the asterisk. From a technical perspective, it says that myFraction is a pointer to a Fraction.

Now that you’ve created an object “container” to store a Fraction, you have to actually create a Fraction to fill that space. You do that in the next line,

`myFraction = [[Fraction alloc] init];`

In this line, you call the alloc method on Fraction; alloc is a class method. Although you never defined the alloc method, it is inherited from NSObject. Inheritance will be discussed in a later lesson.

After you allocate a Fraction, you have to actually initialize it. Therefore, you pass the value of the alloc method to NSObject’s init method, and the resulting Fraction is assigned to myFraction. This nested sequence of messages is used almost every time you create a new object.

Next, you set the values of myFraction to 2 and 5 by using the proper method calls.

```[myFraction setNumerator:2];
[myFraction setDenominator:5];
```

You pass the integers 2 and 5 as arguments to the method. The method then takes these arguments and sets the numerator and denominator variables of myFraction.

You then call myFraction’s showResults method to print the value of the fraction.

We then free up the memory that Fraction uses by calling the release method:

```[myFraction release];
```

This is a critical part of programming for iOS. Whenever you create a new object through alloc/init, you have to release it—in other words, every alloc/init call is balanced by a release call. Otherwise, the now-useless object will still sit in memory, taking up space; in a memory-constrained environment such as the iPhone, you want to use as little memory as you can.

In every message, you send the message to a specific receiver—the object or class which implements the method. However, instance methods are sent to specific instances, so that the same method call to two different Fractions will result in two Fractions with potentially different values. For example,

```[fraction1 setNumerator:2];
[fraction1 setDenominator:5];

[fraction2 setNumerator:3];
[fraction2 setDenominator:4];
```

Will result in two separate fractions, one with a value of 2/5 and another with a value of 3/4. Although you are calling the same methods on both, they are received by different objects, with their own set of numerator and denominator variables.

Data Encapsulation

As mentioned before, you shouldn’t directly access the instance variables of an object. Data encapsulation provides some security against people working with the class, to prevent them from tinkering with the inner workings. So in the main function, how would you access these values?

Generally, you access these values by writing special methods, known as getter methods (the set methods that we’ve already wrote for Fraction are known as setter methods; they are generally written in pairs).

The getter methods for the Fraction class look something like this:

```- (int)numerator;
- (int)denominator;

- (int)numerator {
return numerator;
}
- (int)denominator {
return denominator;
}
```

It doesn’t matter if the method name is the same as the variable name; in fact, it is common practice.

Program 3.3 contains the main function that tests these new methods.

Program 3.3

```int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// Create an instance of Fraction
Fraction *myFraction;

myFraction = [[Fraction alloc] init];

// Set myFraction to 2/5
[myFraction setNumerator:2];
[myFraction setDenominator:5];

// Display the value of myFraction
NSLog (@"The value of myFraction is %d/%d", [myFraction numerator], [myFraction denominator]);

// Clear up memory
[myFraction release];    [pool drain];
return 0;
}
```

The output is

```The value of myFraction is 2/5
```

Objective-C 2.0 introduces properties, which provide an easy way to create getter and setter methods. This will also be covered in a later lesson.

What You Will Learn About Objective-C

So, having decided on doing a course on Objective-C, I’d like to set down some goals.

1. As I mentioned before, I will attempt to teach C and Objective-C as one language. Obj-C is a strict superset of plain C, which means that any valid C is also valid Obj-C. The reason for this decision is that C is a procedural language, where you worry about how you do a task, whereas Obj-C is an object-orientated language, where you worry about what you use to do a task. It’s a radical shift in mindset. As a result, although Obj-C builds smoothly off of plain C, not all C styles and procedures work with Obj-C.
2. I want to engage, not just present the facts. As a result, I will supply plenty of screenshots, and include exercises at the end of each lesson. I will also post the source code to each lesson on this blog—stay tuned for more.
3. I want to create a solid understanding that frees you from having to go back to a reference every other line of code. That gets annoying, and you won’t get much respect in programming circles. 😛
4. I want to make it an easy and fluid learning environment. People learn better when they are subject to less stress. In fact, I’m not going to stress you at all—you’ll be your own motivator. You want to build the next great iPhone app—so put in the effort!

In this course, I hope to build up a small code library, and have each lesson build up off the previous. I still need to plan out the order of the lessons and their content…stay tuned!

Learn Objective-C in 24 Days

Yep, that title says 24 DAYS, not hours. You can’t learn a programming language in 24 hours. Publishers say you can, but that’s just for marketing purposes. To really get to learn a language, to the point where you don’t have to look back through the book every other line, takes time. It takes time to do the exercises. It takes time to formulate questions, and answer them for yourself (although I’ll be glad to answer any to the best of my ability).It takes time to let the language sink in.

I’m starting a series that will attempt to teach the Objective-C language. As Kochan did in his book (see my Resources page), I will attempt to teach plain C and Obj-C as one language. I don’t know how long it’ll take to complete—we’ll see. I want to do a solid job of teaching the language though. This post will be updated as an index of all the lessons. I hope to have the first one out by the end of the week.

My goal is to teach the series at a comfortable pace for most people. I want it to be a fun and engaging experience, and an easy place for beginners to begin their coding journey. As always, comments and criticisms are appreciated.

Directory of Lessons:

• Welcome

My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

• Contact Me

If you need to contact me for any reason, feel free to send me an email.
• The Giving Spirit

If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

• Subscribe

Join 220 other followers

• You count!

• 622,650 views