Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

The program Section

The program section contains the code to solve your particular problem, which can be spread out across many files, if necessary. Somewhere you must have a routine called main, as we've previously noted. That's where your program always begins execution. Here's the program section from Program 3.2:

//---- program section ----

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

   Fraction *myFraction;

   // Create an instance of a Fraction and initialize it

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

   // Set fraction to 1/3

   [myFraction setNumerator: 1];
   [myFraction setDenominator: 3];
   // Display the fraction using the print method

   NSLog (@"The value of myFraction is:");
   [myFraction print];

   [myFraction release];
   [pool drain];

   return 0;
}

Inside main, you define a variable called myFraction with the following line:

Fraction *myFraction;

This line says that myFraction is an object of type Fraction; that is, myFraction is used to store values from your new Fraction class. The asterisk that precedes the variable name is described in more detail below.

Now that you have an object to store a Fraction, you need to create one, just as you ask the factory to build you a new car. This is done with the following line:

myFraction = [Fraction alloc];

alloc is short for allocate. You want to allocate memory storage space for a new fraction. This expression sends a message to your newly created Fraction class:

[Fraction alloc]

You are asking the Fraction class to apply the alloc method, but you never defined an alloc method, so where did it come from? The method was inherited from a parent class. Chapter 8, "Inheritance" deals with this topic in detail.

When you send the alloc message to a class, you get back a new instance of that class. In Program 3.2, the returned value is stored inside your variable myFraction. The alloc method is guaranteed to zero out all of an object's instance variables. However, that doesn't mean that the object has been properly initialized for use. You need to initialize an object after you allocate it.

This is done with the next statement in Program 3.2, which reads as follows:

myFraction = [myFraction init];

Again, you are using a method here that you didn't write yourself. The init method initializes the instance of a class. Note that you are sending the init message to myFraction. That is, you want to initialize a specific Fraction object here, so you don't send it to the class—you send it to an instance of the class. Make sure you understand this point before continuing.

The init method also returns a value—namely, the initialized object. You store the return value in your Fraction variable myFraction.

The two-line sequence of allocating a new instance of class and then initializing it is done so often in Objective-C that the two messages are typically combined, as follows:

myFraction = [[Fraction alloc] init];

This inner message expression is evaluated first:

[Fraction alloc]

As you know, the result of this message expression is the actual Fraction that is allocated. Instead of storing the result of the allocation in a variable, as you did before, you directly apply the init method to it. So, again, first you allocate a new Fraction and then you initialize it. The result of the initialization is then assigned to the myFraction variable.

As a final shorthand technique, the allocation and initialization is often incorporated directly into the declaration line, as in the following:

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

We use this coding style often throughout the remainder of this book, so it's important that you understand it. You've seen in every program up to this point with the allocation of the autorelease pool:

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

Here an alloc message is sent to the NSAutoreleasePool class requesting that a new instance be created. The init message then is sent to the newly created object to get it initialized.

Returning to Program 3.2, you are now ready to set the value of your fraction. These program lines do just that:

// Set fraction to 1/3

[myFraction setNumerator: 1];
[myFraction setDenominator: 3];

The first message statement sends the setNumerator: message to myFraction. The argument that is supplied is the value 1. Control is then sent to the setNumerator: method you defined for your Fraction class. The Objective-C system knows that it is the method from this class to use because it knows that myFraction is an object from the Fraction class.

Inside the setNumerator: method, the passed value of 1 is stored inside the variable n. The single program line in that method stores that value in the instance variable numerator. So you have effectively set the numerator of myFraction to 1.

The message that invokes the setDenominator: method on myFraction follows next. The argument of 3 is assigned to the variable d inside the setDenominator: method. This value is then stored inside the denominator instance variable, thus completing the assignment of the value 1/3 to myFraction. Now you're ready to display the value of your fraction, which you do with the following lines of code from Program 3.2:

// Display the fraction using the print method

NSLog (@"The value of myFraction is:");
[myFraction print];

The NSLog call simply displays the following text:

The value of myFraction is:

The following message expression invokes the print method:

[myFraction print];

Inside the print method, the values of the instance variables numerator and denominator are displayed, separated by a slash character.

The message in the program releases or frees the memory that was used for the Fraction object:

[myFraction release];

This is a critical part of good programming style. Whenever you create a new object, you are asking for memory to be allocated for that object. Also, when you're done with the object, you are responsible for releasing the memory it uses. Although it's true that the memory will be released when your program terminates anyway, after you start developing more sophisticated applications, you can end up working with hundreds (or thousands) of objects that consume a lot of memory. Waiting for the program to terminate for the memory to be released is wasteful of memory, can slow your program's execution, and is not good programming style. So get into the habit of releasing memory when you can right now.

The Apple runtime system provides a mechanism known as garbage collection that facilitates automatic cleanup of memory. However, it's best to learn how to manage your memory usage yourself instead of relying on this automated mechanism. In fact, you can't rely on garbage collection when programming for certain platforms on which garbage collection is not supported, such as the iPhone or iPad. For that reason, we don't talk about garbage collection until much later in this book.

It seems as if you had to write a lot more code to duplicate in Program 3.2 what you did in Program 3.1. That's true for this simple example here; however, the ultimate goal in working with objects is to make your programs easier to write, maintain, and extend. You'll realize that later.

Let's go back for a second to the declaration of myFraction

Fraction *myFraction;

and the subsequent setting of its values.

The asterisk (*) in front of myFraction in its declaration says that myFraction is actually a reference (or pointer) to a Fraction object. The variable myFraction doesn't actually store the fraction's data (that is, its numerator and denominator values). Instead, it stores a reference—which is a actually a memory address—indicating where the object's data is located in memory. When you first declare myFraction as shown, its value is undefined as it has not been set to any value and does not have a default value. We can conceptualize myFraction as a box that holds a value. Initially the box contains some undefined value, as it hasn't been assigned any value. This is depicted in Figure 3.2.

Figure 3.2

Figure 3.2 Declaring

Fraction *myFraction;

When you allocate a new object (using alloc, for example) enough space is reserved in memory to store the object's data, which inclues space for its instance variables, plus a little more. The location of where that data is stored (the reference to the data) is returned by the alloc routine, and assigned to the variable myFraction. This all takes place when this statement in executed in Program 3.2.

myFraction = [Fraction alloc];

The allocation of the object and the storage of the reference to that object in myFraction is depicted in Figure 3.3:

Figure 3.3

Figure 3.3 Relationship between myFraction and its data

Notice the directed line in Figure 3.3. This indicates the connection that has been made between the variable myFraction and the allocated object. (The value stored inside myFraction is actually a memory address. It's at that memory address that the object's data is stored.)

Subsequently in Program 3.2, the fraction's numerator and denominator are set. Figure 3.4 depicts the fully initialized Fraction object with its numerator set to 1 and its denominator set to 3.

Figure 3.4

Figure 3.4 Setting the fraction's numerator and denominator

The next example shows how you can work with more than one fraction in your program. In Program 3.3, you set one fraction to 2/3, set another to 3/7, and display them both.

Program 3.3.

// Program to work with fractions – cont'd

#import <Foundation/Foundation.h>

//---- @interface section ----

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

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

@end

//---- @implementation section ----

@implementation Fraction
-(void) print
{
   NSLog (@"%i/%i", numerator, denominator);
}

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

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

//---- program section ----

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

   Fraction *frac1 = [[Fraction alloc] init];
   Fraction *frac2 = [[Fraction alloc] init];

   // Set 1st fraction to 2/3

   [frac1 setNumerator: 2];
   [frac1 setDenominator: 3];

   // Set 2nd fraction to 3/7

   [frac2 setNumerator: 3];
   [frac2 setDenominator: 7];

   // Display the fractions

   NSLog (@"First fraction is:");
   [frac1 print];

   NSLog (@"Second fraction is:");
   [frac2 print];

   [frac1 release];
   [frac2 release];

   [pool drain];
   return 0;
}

Program 3.3. Output

First fraction is:
2/3
Second fraction is:
3/7

The @interface and @implementation sections remain unchanged from Program 3.2. The program creates two Fraction objects, called frac1 and frac2, and then assigns the value 2/3 to the first fraction and 3/7 to the second. Realize that when the setNumerator: method is applied to frac1 to set its numerator to 2, the instance variable frac1 gets its instance variable numerator set to 2. Also, when frac2 uses the same method to set its numerator to 3, its distinct instance variable numerator is set to the value 3. Each time you create a new object, it gets its own distinct set of instance variables. Figure 3.5 depicts this.

Figure 3.5

Figure 3.5 Unique instance variables

Based on which object is getting sent the message, the correct instance variables are referenced. Therefore, here frac1's numerator is referenced whenever setNumerator: uses the name numerator inside the method:

[frac1 setNumerator: 2];

That's because frac1 is the receiver of the message.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020