Advertisements

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.

Advertisements
Leave a comment

10 Comments

  1. Shoaib

     /  March 17, 2013

    Hello,
    When I type NSAutoreleasePool, xCode tells me that this is unavailable in auto reference counting mode. Please help me understand what this means. Im a complete NOOB.

    Reply
  2. When I run this program as mentioned, I get the following errors, in the fractiondemo.m file,
    /Users/rvadlama/Documents/ios/objectiveC tutorial/objectiveC programs/fractionDemo/fractionDemo.m:7:0 /Users/rvadlama/Documents/ios/objectiveC tutorial/objectiveC programs/fractionDemo/fractionDemo.m:7: error: ‘Fraction’ undeclared (first use in this function)

    /Users/rvadlama/Documents/ios/objectiveC tutorial/objectiveC programs/fractionDemo/fractionDemo.m:7:0 /Users/rvadlama/Documents/ios/objectiveC tutorial/objectiveC programs/fractionDemo/fractionDemo.m:7: error: ‘myFraction’ undeclared (first use in this function)

    Not sure, what I am doing wrong here. Can you please guide me?

    Reply
    • My guess is that you forgot to

      import "Fraction.h"

      in the .m file. You have to bring in the declaration in the header so Xcode knows what you’re talking about in the implementation.

      Reply
  3. Bill

     /  May 4, 2013

    I’ve done #import “Fraction.h” but I’m getting ‘Fraction.h’ file not found. Any suggestions?

    Reply
    • Bill

       /  May 5, 2013

      Don’t worry, sorted it. Just a note though, to get it to work I had to remove the #import on the second line of code in ‘main.m’ file.
      Great tutorial, feel I am getting to grips with the basics.

      Reply
  4. Tommy

     /  May 17, 2013

    I always get on the first line Fraction.h file not found so I’m not able to compile.

    Reply
    • Tommy

       /  May 17, 2013

      Forget it I find my answer! I tried to run the program only with the first section.

      Reply
  1. Objects (Part 2): Properties « Programming for iOS
  2. Learn Objective-C in 24 Days « Programming for iOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Advertisements
  • 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!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 222 other followers

  • Back to the Past

    December 2010
    S M T W T F S
    « Nov   Jan »
     1234
    567891011
    12131415161718
    19202122232425
    262728293031  
  • Time Machine

  • You count!

    • 621,851 views
  • Worldwide Stats

    free counters
  • Advertisements
%d bloggers like this: