# Objects (Part 1): Splitting Classes Into Multiple Files

This is the first in a multi-part series that will talk about the fundamentals of objects. If you’re still keeping track, I suppose these would all fall under Lesson 6: Objects.

In Lesson 3, we began a simple overview to object-oriented programming. Now, we’ve covered the major portions of the basic language—what is “plain C.” There are other topics, such as structs, arrays, and a slew of other rather obscure topics. Some of these are enclosed or remade in the code the Apple provides for free; others will be discussed as necessary. For now, we will start venturing into the exciting world of objects—and they really are exciting.

As part of our calculator, we will allow the calculator to operate on regular values, as well as fractions. For the sake of demonstration, we will begin by creating Fraction objects.

# Creating the Test Code

Create a new Xcode project. In the New Project window, choose “Application” under Mac OS X from the left side, then choose “Command Line Tool” from the top right, and make sure the “Type” is set to Foundation. Click Choose, and save it as “FractionDemo” anywhere you choose. In the File List, load FractionDemo.m, and enter the following code:

```#import "Fraction.h"
#import

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

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

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

// Display the value of myFraction
NSLog(@"myFraction has a value of: ");
[myFraction display];

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

Here, you can see that in our main code body, we create an object of type Fraction, and call it myFraction. Ignore the asterisk (* for now; it is a sign that you are actually creating a pointer…that’s an advanced topic that will be further explored later). You set myFraction to the value returned from the standard alloc/init method call.

Next, we call the methods setNumerator: and setDenominator: and pass both integer values; these methods will set the appropriate values of the Fraction object we’ve created. We then send another message call for myFraction to display itself (or so we assume, based on the method name—make sure to write descriptive method names). Then we release our object—don’t worry about the memory management for now.

Now, we will create the actual Fraction object itself.

# Creating the Fraction Class

In Xcode, Go to File > New File (⌘N). From the left, choose Cocoa Class under Mac OS X, select Objective-C class from the top left, and make it a Subclass of NSObject. Click Next, and set the following parameters:

1. Set the File Name to be “Fraction.m”. Note that the “.m” part is automatically added; just type “Fraction”, without the quotes, making sure that the “F” is capitalized. By convention, class names are capitalized.
2. Make sure that ‘Also create “Fraction.h”‘ is selected.
3. Leave the default settings for the other fields. Add to Project should display “FractionDemo,” the name of your project, and in your Targets window, the checkbox to the left of the “FractionDemo” entry should be selected.

Click “Finish”. In your File List, you will see two new files: “Fraction.h” and “Fraction.m.” Select Fraction.h, and enter the following code:

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

@interface Fraction : NSObject {
NSInteger numerator;
NSInteger denominator;
}
- (void)setNumerator:(NSInteger)value;
- (void)setDenominator:(NSInteger)value;
- (void)display;

@end
```

Here we define two instance variables, called “numerator” and “denominator”. They are defined as type NSInteger; this is identical to the standard int type; there’s really no difference. My personal preference is NSInteger.

Next, we define the methods that we call in the main() method. There should not be anything new here, if you’ve read through Lesson 3.

In Fraction.m, enter the following code:

```#import "Fraction.h"

@implementation Fraction
- (void)setNumerator:(NSInteger)value {
numerator = value;
}

- (void)setDenominator:(NSInteger)value {
denominator = value;
}

- (void)display {
NSString *numeratorString = [[NSString alloc] initWithFormat:@"%d", numerator];
NSString *denominatorString = [[NSString alloc] initWithFormat:@"%d", denominator];
NSLog(@"%@/%@", numeratorString, denominatorString);
[denominatorString release];
[numeratorString release];
}

@end
```

Chewing through this code, the first two methods should not present anything new. The last method does warrant some discussion, however.

If you refer back to Lesson 3, you’ll notice that we defined the display method (we called it showResults there) as

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

Our display method shows a different way to do this. First, we highlight NSString’s initWithFormat: method, which works like NSLog() does, except that instead of outputting, it is saved as a string. In the actual NSLog(), we use the %@ format specifier, which takes an NSString as an argument. Finally, we have to release the NSStrings that we’ve created…again, don’t worry about the memory management at the moment.

If we Build and Run now, we get the following output:

```myFraction has a value of:
2/5```

This is exactly what we’re looking for.

You’ll notice that we haven’t really done anything new since Lesson 3. In fact, that is true, except that we have created a Fraction class in separate files. Looking back over the code entries, the bold lines show where the dependencies lie—in a class’s .m file, it #imports the correspond .h (known as the ‘header’) file. In any file that uses the class you’ve created, you also need to import the header. Here, you’ve made it easier to maintain a larger project; as we add more classes, you won’t be working with one gigantic file.

# Shameless Self-Promotion

To get the word out, I’d generally rely on search engines. And I can’t afford to pay Google to get listed (and most of those ads aren’t exactly reputable anyway). So, here’s some shameless self promotion. I promise I won’t really do this much more. Feel free to not read this. You may want to entertain yourself elsewhere (I’d recommend Uncyclopedia).

Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa

iPhone App Development iPhone App Development iPhone App Development iPhone App Development

iPhone Application Development iPhone Application Development iPhone Application Development

Programming for iOS Programming for iOS Programming for iOS Programming for iOS Programming for iOS

iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App

iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps

Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps

iPhone Programming iPhone Programming iPhone Programming iPhone Programming iPhone Programming iPhone Programming

Developer Developer Developer Developer Developer Developer Developer Developer Developer Developer Developer

iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS

App Store App Store App Store App Store App Store App Store App Store App Store App Store App Store App Store

Programming Programming Programming Programming Programming Programming Programming

iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone

iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch

Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode

Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C

Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple

Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa

iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK

Software Software Software Software Software Software Software Software Software Software Software

Object-Oriented Programming Object-Oriented Programming Object-Oriented Programming Object-Oriented Programming

😀

# Objective-C Lesson 1: Hello World!

Note: Click on any image to see a larger version.

Since Dennis Ritchie demoed the C programming language, it has been conventional to begin a programming course with a program that writes the words “Hello world!” to the computer screen. Diving right in, the code is shown below.

Program 1.1

```// First program example

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog (@"Hello, World!");
[pool drain];
return 0;
}```

# Using Xcode

So what does all this gibberish mean? Before we can get to that, we’ll run the program first.

Download a copy of Xcode, if you don’t have it already, and install it. Navigation to your boot drive (usually Macintosh HD), and the folder called Developer. Inside, there will be a folder called Applications. Xcode, and some other programs you will be using, is in there.

Location of Xcode.app

Drag it to your dock, or create an alias for it in your Applications folder. Launch Xcode. The first thing you’ll see is the launch window:

Xcode Launch Window (New Project Highligted)

Click on “Create a new Xcode project,” or select File > New Project (⇧⌘N). The button is highlighted in the image above. You will be greeted by the following window:

Xcode's New Image Window

Select Application under Mac OS X on the left, and choose Command Line Tool on the right. Make sure the Type drop-down menu in the middle is set to Foundation. Click Choose…

Name your project, and save it somewhere on your hard drive. In a few moments, you’ll see Xcode’s main interface:

Xcode's Main Window

We’ll take more about the parts of the window in later sections. Click on the file called Hello World.m, or something similar. This should bring up the editor window. Replace the code in the editor view with the code above, so that it looks like this:

The Code in Xcode's Editor

Don’t worry about all the colors—we’ll discuss that later. When you have entered the code, save the file, and click the “Build and Run” or “Build and Go” button in the toolbar.

If you’ve made a mistake when typing it in, the toolbar at the bottom of Xcode’s window will change, and a message bubble will appear:

Go back, and check the code.

When everything is working, you’ll see yet another window:

Xcode Displays the Result of the Program

The output is as follows:

`2010-09-03 10:47:32.414 Hello World[25379:a0f] Hello, World!`

The beginning of the line shows the date and time, followed by the name of the program, and bunch of gibberish. But at the end of the line is the text that you expected to see: The program has written the words “Hello, World!” onto the screen.

Throughout the rest of these tutorials, the text that appears before that actual text that is outputted will be omitted for brevity.

# Code, Demystified

Now that you’ve created a working program, let’s talk about how it works.

In Objective-C, a capital and lowercase letter mean different things. So, main, Main, and mAin are three completely different things, and cannot be used interchangeably. Also note that white space—spaces, tabs, and blank lines are ignored. You can use this to format your code properly. Take advantage of this freedom to properly format your code.

The first line of the program is a comment:

`// First program example`

Comments exist solely for the benefit of the programmer. Comments are important, because they allow the developer to explain a thought process. They help demystify the code, and make documenting the code sometime down the road easier. Comments help during the debugging process, or when you revisit your code some time later. It also helps other people who may use your code understand why things are the way the are. The compiler ignores comments, so you can type anything into a comment.

There are two types of comments in Objective-C. One is shown above, in which every line of the comment is preceded by two slashes. This type of comment ends at the end of the line.

A comment can also be written across multiple lines, with the following syntax:

```/*
A multi-line comment can be inserted
by using a slash
and then an asterisk.
The comment can be as long as you want,
but make sure you close it
with an asterisk, then a slash. */```

Which style you choose is a matter of preference, or as the situation dictates.

The next line of the program imports, or brings into your project, a file called Foundation.h:

`#import <Foundation/Foundation.h>`

The file in question is a system file, and that is why the name is enclosed in the brackets < and >. If you were importing a local file , you would enclose the file name in double quotes “ and ”.  This file is imported because code later in the file requires information that is contained in this file;  you are telling the compiler to look up the information in that file as necessary.

The following line declares a function called main:

`int main (int argc, const char * argv[])`

main is a function that is where every C or C-based program begins. It is a reserved name, which means that you can’t have a function named main. The word int that precedes main is a declaration of the return type of the function. These topics will be discussed in further chapters.

After identifying main to the compiler, you tell the system what to do when it is called. These statements are enclosed in the braces { and } that surround the next few lines. Every opening brace has to be matched with a closing brace.

The first statement in main is as follows:

`NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];`

This involves memory management, which is a topic thoroughly discussed in upcoming chapters.

The next line calls NSLog, which, along with the NSAutoreleasePool from above, is a function brought in by Foundation.h, which you imported.

`NSLog (@"Hello, World!");`

This line tells the function NSLog, which is designed to output text, to print the characters Hello, World! on the screen.

The leading @ in front of the string signifies to the compiler that this is an NSString (another object brought in from the Foundation.h file), not a C-style string. For the most part, you will be using NSStrings, rather than C-style strings.

All statements, or lines that indicate some action, must be terminated with a semicolon ; just like regular sentences are terminated with a period.

The next line is part of the NSAutoreleasePool, and its purpose and meaning will be discussed in a later chapter.
The final line tells the main method to return the value 0. Remember that the int the preceded main tells the system that this function will return a value. This value is 0. By convention, a return value of zero indicates that the function was successful.

`return 0;`

This line is followed by a closing brace, signifying the end of the main function.

If you look back at the window that displays the output of your program, you should see the line

`Program exited with status value:0.`

This is an indication of the return value of main.

Congratulations, you have created your first program in Objective-C!

# Get a Copy of Xcode (It’s Free)

1. Visit the Apple Developer Connection site.
2. If you already have an account, log in to the iPhone Development Center using the blue buttons near the bottom of the page. Go to step 5.
3. Register as an iPhone developer. If you plan on selling your apps, register as a standard developer. (It will cost \$99 a year. It’s totally worth it). For most people, you can just register as a free developer. The difference (for now) is that the free version does not let you test your apps on device; you’re limited to the Simulator. That’ll work fine for the majority of topics I plan to cover here.
4. Follow through the steps. They’re pretty self explanatory. Fill in your profile, agree to the agreement, and check your email for a verification code. Congrats—you’re now a registered Apple developer!
6. Download the SDK (the link is in the second rectangle on the left, about 2/3 of the way down the page). The latest version as of this writing is iOS SDK 4.0.2. If you have Snow Leopard, download that version. The Leopard version contains a different subset of features.
7. Install it, and you’re good to go!
• ## 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!