05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

488<br />

CHAPTER 26 MAC <strong>OS</strong> X DEVELOPMENT: OBJECTIVE-C<br />

Object-Oriented Programming<br />

with Objective-C<br />

Projects written with procedural languages, such as C, become very difficult to understand as<br />

they grow larger. Object-oriented programming languages, such as Objective-C, offer a way to<br />

organize code into structured units called classes. From a C perspective, a class is like a struct, a<br />

typedef, and a library of functions all rolled into one. An object is an individual instance of<br />

a class.<br />

Other than that broad review, the tenets of object-oriented programming are beyond the<br />

scope of this book. Fortunately, it’s something most developers should already be familiar with.<br />

What’s important to the topic at hand are the ways Objective-C implements those tenets and the<br />

advantages Objective-C offers, compared to other object-oriented languages.<br />

Declaring an Interface<br />

Let’s look at the header of a simple Objective-C class:<br />

#import <br />

@interface BMPerson : NSObject {<br />

NSString *name;<br />

NSUInteger age;<br />

}<br />

+ (BMPerson *)personWithName:(NSString *)aName age:(NSUInteger)anAge;<br />

- (NSString *)name;<br />

- (void)setName:(NSString *)aName;<br />

- (NSUInteger)age;<br />

- (void)setAge:(NSUInteger)anAge;<br />

@end<br />

The first thing you need to do is import your application frameworks. For convenience, you<br />

can just import the entirety of Cocoa:<br />

#import <br />

The #import directive is an improved version of C’s #include directive that will add the<br />

header files only if they have not already been defined.<br />

You begin the interface with the declaration @interface, name the class BMPerson, and use the<br />

: operator to set its superclass to NSObject:<br />

@interface BMPerson : NSObject {<br />

NOTE Objective-C does not use namespaces, so class names start with a (usually two-letter)<br />

prefix to reduce the chance of overlap. Since we’re going beyond the manual, we’ll go with BM,<br />

but you should choose something appropriate, such as your initials, the initials of your company,<br />

or something germaine to your project.<br />

The brace opens the composition section, where we declare instance variables, also known<br />

as ivars. We can use object types by declaring a pointer to the type.<br />

NSString *name;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!