Home > Articles > Programming > C/C++

Objective-C Boot Camp

This chapter is from the book

Classes and Objects

Objects form the heart of object-oriented programming. You define objects by building classes, which act as object-creation templates. In Objective-C, a class definition specifies how to build new objects that belong to the class. So to create a “widget” object, you define the Widget class and then use that class to create new objects on demand.

Each class lists its instance variables and methods in a public header file using the standard C .h convention. For example, you might define a Car object like the one shown in Listing 3-1. The Car.h header file shown here contains the interface that declares how a Car object is structured. Note that all classes in Objective-C should be capitalized.

Listing 3-1. Declaring the Car Interface (Car.h)

#import <Foundation/Foundation.h>
@interface Car : NSObject
    int year;
    NSString *make;
    NSString *model;
- (void) setMake:(NSString *) aMake andModel:(NSString *) aModel
    andYear: (int) aYear;
- (void) printCarInfo;
- (int) year;

In Objective-C, the @ symbol is used to indicate certain keywords. The two items shown here (@interface and @end) delineate the start and end of the class interface definition. This class definition describes an object with three instance variables: year, make, and model. These three items are declared between the braces at the start of the interface.

The year instance variable is declared as an integer (using int). Both make and model are strings, specifically instances of NSString. Objective-C uses this object-based class for the most part rather than the byte-based C strings defined with char *. As you see throughout this book, NSString offers far more power than C strings. With this class, you can find out a string’s length, search for and replace substrings, reverse strings, retrieve file extensions, and more. These features are all built into the base Cocoa Touch object library.

This class definition also declares three public methods. The first is called setMake:andModel:andYear:. This entire three-part declaration, including the colons, is the name of that single method. That’s because Objective-C places parameters inside the method name. In C, you’d use a function such as setProperties(char *c1, char *c2, int i). Objective-C’s approach, although heftier than the C approach, provides much more clarity and self-documentation. You don’t have to guess what c1, c2, and i mean because their use is declared directly within the name:

[myCar setMake:c1 andModel:c2 andYear:i];

The three methods are typed as void, void, and int. As in C, these refer to the type of data returned by the method. The first two do not return data; the third returns an integer. In C, the equivalent function declaration to the second and third method would be void printCarInfo() and int year();.

Using Objective-C’s method-name-interspersed-with-arguments approach can feel odd to new programmers but quickly becomes a much-loved feature. There’s no need to guess which argument to pass when the method name itself tells you what items go where. In Objective-C, method names are also interchangeably called “selectors.” You see this a lot in iOS programming, especially when you use calls to performSelector:, which lets you send messages to objects at runtime.

Notice that this header file uses #import to load headers rather than #include. Importing headers in Objective-C automatically skips files that have already been added. This lets you add duplicate #import directives to your various source files without any penalties.

Creating Objects

To create an object, you tell Objective-C to allocate the memory needed for the object and return a pointer to that object. Because Objective-C is an object-oriented language, its syntax looks a little different from regular C. Instead of just calling functions, you ask an object to do something. This takes the form of two elements within square brackets, the object receiving the message followed by the message itself:

[object message]

Here, the source code sends the message alloc to the Car class and then sends the message init to the newly allocated Car object. This nesting is typical in Objective-C.

Car *myCar = [[Car alloc] init];

The “allocate followed by init” pattern you see here represents the most common way to instantiate a new object. The class Car performs the alloc method. It allocates a new block of memory sufficient to store all the instance variables listed in the class definition, zeroes out any instance variables, and returns a pointer to the start of the memory block. The newly allocated block is called an “instance” and represents a single object in memory.

Some classes, like views, use specialized initializers such as initWithFrame:. You can write custom ones, such as initWithMake:andModel:andYear:. The pattern of allocation followed by initialization to create new objects holds universally. You create the object in memory and then you preset any critical instance variables.

Memory Allocation

In this example, the memory allocated is 16 bytes long. Both make and model are pointers, as indicated by the asterisk. In Objective-C, object variables point to the object itself. The pointer is 4 bytes in size. So sizeof(myCar) returns 4. The object consists of two 4-byte pointers, one integer, plus one additional field that does not derive from the Car class.

That extra field is from the NSObject class. Notice NSObject at the right of the colon next to the word Car in the class definition of Listing 3-1. NSObject is the parent class of Car, and Car inherits all instance variables and methods from this parent. That means that Car is a type of NSObject and any memory allocation needed by NSObject instances is inherited by the Car definition. So that’s where the extra 4 bytes come from.

The final size of the allocated object is 16 bytes in total. That size includes two 4-byte NSString pointers, one 4-byte int, and one 4-byte allocation inherited from NSObject. You can easily print out the size of objects using C’s sizeof function. This code uses standard C printf statements to send text information to the console. printf commands work just as well in Objective-C as they do in ANSI C.

NSObject *object = [[NSObject alloc] init];
Car *myCar = [[Car alloc] init];

// This returns 4, the size of an object pointer
printf("object pointer: %d\n", sizeof(object));

// This returns 4, the size of an NSObject object
printf("object itself: %d\n", sizeof(*object));

// This returns 4, again the size of an object pointer
printf("myCar pointer: %d\n", sizeof(myCar));

// This returns 16, the size of a Car object
printf("myCar object: %d\n", sizeof(*myCar));

Releasing Memory

In C, you allocate memory with malloc() or a related call and free that memory with free(). In Objective-C, you allocate memory with alloc and free it with release. (In Objective-C, you can also allocate memory a few other ways, such as by copying other objects.)

[object release];
[myCar release];

As discussed in Chapter 2, “Building Your First Project,” releasing memory is a little more complicated than in standard C. That’s because Objective-C uses a reference-counted memory system. Each object in memory has a retain count associated with it. You can see that retain count by sending retainCount to the object, although in the real world you should never rely on using retainCount in your software deployment. It’s used here only as a tutorial example to help demonstrate how a retain count works.

Every object is created with a retain count of 1. Sending release reduces that retain count by 1. When the retain count for an object reaches 0, or more accurately, when it is about to reach 0 by sending the release message to an object with a retain count of 1, it is released into the general memory pool.

Car *myCar = [[Car alloc] init];

// The retain count is 1 after creation
printf("The retain count is %d\n", [myCar retainCount]);

// This would reduce the retain count to 0, so it is freed instead
[myCar release];

// This causes an error. The object has already been freed
printf("Retain count is now %d\n", [myCar retainCount]);

Sending messages to freed objects will crash your application. When the second printf executes, the retainCount message is sent to the already-freed myCar. This creates a memory access violation, terminating the program. As a general rule, it’s good practice to assign instance variables to nil after the final release that deallocates the object. This prevents the FREED(id) error you see here when you access an already-freed object:

The retain count is 1
objc[10754]: FREED(id): message retainCount sent to freed

There is no garbage collection on iOS SDK. As a developer, you must manage your objects. Keep them around for the span of their use and free their memory when you are finished. Read more about basic memory management strategies later in this chapter.

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.


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.


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.


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.


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


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


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.


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.


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