2
Objective-C

iOS applications are written in the Objective-C language using the Cocoa Touch library. Objective-C is a simple extension of the C language and Cocoa Touch is a collection of Objective-C classes. This book assumes you know some C and understand the ideas of object-oriented programming. If C or object-oriented programming makes you feel uneasy, we recommend starting with Objective-C Programming: The Big Nerd Ranch Guide.

In this chapter, you will learn the basics of Objective-C and create a command line tool called RandomPossessions. You’ll reuse parts of this tool in an iOS application starting in Chapter 10, so even if you’re familiar with Objective-C, you should still go through this chapter in order to create RandomPossessions.

Objects

Let’s say you need a way to represent a party. Your party has a few attributes that are unique to it, like a name, a date, and a list of invitees. You can also ask the party to do things like send an email reminder to all the invitees, print name tags, or cancel the party altogether.

In C, you would define a structure to hold the data that describes a party. The structure would have data members – one for each of the party’s attributes. Each data member would have a name and a type.

To create an individual party, you would use the function malloc to allocate a chunk of memory large enough to hold the structure. You would write C functions to set the value of its attributes and have it perform actions.

In Objective-C, instead of using a structure to represent a party, you use a class. A class is like a cookie-cutter that produces objects. The Party class creates objects, and these objects are instances of the Party class. Each instance of the Party class can hold the data for a single party (Figure 2.1).

Figure 2.1  A class and its instances

A class and its instances

An instance of Party, like all objects, is a chunk of data stored in memory, and it stores the values for its attributes in instance variables. So an instance of Party might have the following instance variables: name, date, budget.

A C structure is a chunk of memory, and so is an object. A C structure has data members, each with a name and a type. Similarly, an object has instance variables, each with a name and a type.

But there is an important difference between a structure in C and a class in Objective-C – a class has methods. A method is similar to a function: it has a name, a return type, and a list of parameters that it expects. A method also has access to an object’s instance variables. If you want an object to run the code in one of its methods, you send that object a message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.29.126