Mac OS X Development: The Application Frameworks

Một phần của tài liệu Mac OS x leopard (Trang 447 - 473)

Objective-C, a revolutionary programming language that combines the design advantages of an object-oriented language with the flexibility of a low-level language, the dynamism of a scripting language, and a revolution in readability that almost makes comments obsolete.

Figure 24-1.Great applications are built with great tools.

We’ll talk about Interface Builder and Objective-C in the next couple of chapters. For now, let’s focus on some of the frameworks that make creating professional applications in Cocoa so easy.

NOTE Cocoa is only one of several application frameworks on Mac OS X, but you don’t have to worry about whether something is technically Cocoa, a shared framework with a Cocoa interface, or part of another application framework altogether. You can use them all from your Cocoa application, thanks largely to the flexibility of Objective-C.

Application Kit

Just as its name implies, the Application Kit (or AppKit, as it is known to its friends) is a collec- tion of prebuilt components common to many applications. Developers can cobble together a completely functional, if uninteresting, application by snapping together components, like those shown in Figure 24-2. Only Swedish furniture rivals the ease of assembly offered by AppKit.

Figure 24-2.Cocoa components in Interface Builder

AppKit’s components are not just tangible UI widgets like menus, windows, and buttons.

Some of the other things AppKit provides are the following:

• Data visualization objects like tables, browsers, and matrices.

• Abstract objects like controllers, timers, and formatters.

• Document creation, management, and persistence.

• Text handling, including editing, spell checking, and typesetting.

• Graphics handling for images, multimedia, and animation.

• Functionality such as event handling, undo management, and threading.

• System interaction such as printing, pasteboard (clipboard) operations, and scripting.

Most of AppKit’s features can be had with little or no code. Customization can be accom- plished with simple configuration, either as needed by the developer, or at runtime in accordance with user preferences.

Despite all this simplicity, AppKit is also quite flexible. Because AppKit is object-oriented, anything it offers can be subclassed, letting developers customize as much, or as little, as they need.

Foundation

High-level application toolkits are all well and good, but even with all the basics and some of the not-so-basics done for you, you’re still going to have to sit down and write some code. When that inevitability occurs, you need AppKit’s fraternal twin, Foundation.

The Foundation classes are so legion as to be beyond the scope of this book. (Literally!

Apple’s Foundation documentation is over 2,200 pages long.) However, as you might expect, from 60,000 feet it looks a lot like a bulleted list:

• Basic data types such as strings, numbers, and raw data

• Specialized data types like dates, URLs, and time zones

• Basic collections like arrays, sets, and dictionaries

CHAPTER 24MAC OS X DEVELOPMENT: THE APPLICATION FRAMEWORKS 423

• Specialized collections like character sets, index sets, and pointer arrays

• Data loading—local and networked, synchronous and asynchronous

• Data manipulation, conversion, transformation, and formatting

• XML parsing, editing, and transformation

• System functions like run loops, threads, and timers

• Interprocess communications via pipes, ports, and notifications

• Language services like exceptions, garbage collection, and messaging

It’s not called Foundation for nothing. AppKit and the rest of Cocoa are built on top of Foundation. This follows the general trend in Mac OS X development: Apple creates tools, and then uses those tools to make easy-to-use frameworks. Then, it gives developers the tools as well, so they can modify or add as they see fit.

Foundation, while extensive, might not seem so different from any other basic library. In practice, however, Foundation is designed with the same ease of use and snap-together design as AppKit. The classes try to maintain similar interfaces, so, for example, if you decide to refactor an array into a set, there’s very little effort involved.

Since the interfaces are predictable, it’s easy to keep Foundation in your head, despite its breadth. And since it’s written in Objective-C, it’s extremely easy to figure out how to use a method without having to constantly go back to the documentation.

As with AppKit, Objective-C also makes Foundation classes customizable via subclassing and categorization (one of the many tricks outlined in the section on Objective-C), so no matter what you need to do, you’re rarely, if ever, stuck having to roll your own.

Core Data

A lot of people had a lot of reasons why Apple could never transition their architecture from PowerPC to Intel. Yet, when they did just that, most of those reasons ended up being non-issues.

For example, the fact that the two architectures read bytes of binary code in opposite directions (the so-called endianness issue) ended up not affecting most developers at all.

The reason is abstraction. By using high-level frameworks like AppKit and Foundation, developers are protected from implementation details like byte order. The Core Data framework takes that idea a step further by abstracting applications from even their own data.

Traditionally, the system is ignorant of an application’s objects and what they’re doing.

Whether you’ve got a word processing document, a photo album, or a dungeon-roaming adven- turer in a mystical land beyond time and space, to the system they’re all just ones and zeros. You can ask the system to write those ones and zeros to disk, and you can ask it to read them back, but when it comes to interpreting what they mean and how the user’s actions affect them, you’re on your own.

Core Data establishes a generalized object model. As long as your objects conform to that model, the system can tell enough about them to handle many aspects of their lives with little or no intervention on your part. For example, undo and redo, traditionally one of the harder prob- lems to deal with, is free in Core Data.

One of the first things you learn in system design is how to plan your objects, their struc- tures, and their relationships in an entity relationship diagram (ERD). Xcode, Apple’s integrated development environment, even provides a graphical ERD tool, as shown in Figure 24-3. With Core Data, drawing an ERD doesn’t just plan your objects, it also implements them. You can even drag entities out of the ERD into Interface Builder, and Core Data will generate your entire user interface!

Figure 24-3.Core Data modeling in Xcode

Of course, Core Data is best known for persistence. When the user clicks the Save button, you’ve got to decide if that data is going to be written out in some binary format, converted to human-readable XML, or stored in a relational database. Each has its advantages and disadvan- tages, but choose wisely, for once you pick a persistence model, you’re stuck with it.

Well, that’s not entirely true. Nothing is going to stop you from throwing out your XML code and rewriting the whole thing to use relational database. Nothing, that is, except time, money, and a tremendous amount of wasted effort.

With Core Data, changing your persistence model is as simple as changing your mind. You haven’t written any code to read and write data, nor to communicate with any database. Core Data handles all that dirty business for you, so if you want to develop with easily debugged XML, and then switch to a database for performance, you can.

And if you do decide to use a database, you don’t have to worry about installing a database management system onto your users’ machines, because all that stuff is already built into Mac OS X. Oh yeah, and you don’t have to write, think in, or even be aware of the existence of SQL.

Image Kit

Sometimes an application’s functionality becomes so beloved that it finds itself being copied, in whole or in part, in all kinds of other places. Consider photo management, once synonymous with iPhoto. Now you can take pictures in iChat, apply filters in Photo Booth, and view slideshows in Mail.

When this happens, Apple may factor out that functionality into a “kit” framework. Think of it as an application without an interface that you can embed into your own application. With Leopard’s new Image Kit, you can embed all the photo management functionality of iPhoto in your own application, as shown in Figure 24-4.

CHAPTER 24MAC OS X DEVELOPMENT: THE APPLICATION FRAMEWORKS 425

Figure 24-4.Image Kit’s image browser in Interface Builder

Here are some of the classes provided by Image Kit:

• Browser for viewing a large number of images in a grid view, similar to iPhoto

• Slideshow for viewing and working with multiple images sequentially

• View optimized for images, with controls for zooming, rotating, and cropping

• Edit panel for changing image properties and applying some basic effects

• Filter application and UI elements for browsing and using filters

• Save panel addition that presents specialized options based on the format of the image data

• Picture taker, like the one found in iChat and Photo Booth

Aside from providing some great functionality, Image Kit is built on the latest Mac OS X graphics libraries. That means, aside from having the animated translucent look of a next- generation application, its interfaces are able to optimize performance for modern graphics cards, using things like hardware acceleration, when available.

Similarly, it uses the same nondestructive Core Image filters found throughout the system, so as Apple or other developers add new filters, your applications pick them up as well, with no extra effort on your part.

That also applies to image formats. Already, Image Kit can also handle icons, movies, PDF documents, and even Quartz Composer compositions.

NOTE For more information on iPhoto and Image Capture, check out Chapter 16.

Accelerate

Imagine yourself in the future, a happy and productive Cocoa programmer. You’ve already fin- ished this book, including the section on Apple’s optimization tools, so you knew better than to think about performance while you were blasting out your killer new application.

Now, ahead of schedule and under budget, you’ve carefully profiled away all the major per- formance bottlenecks, but one tight loop is giving your trouble. You reach for your book on assembly language . . .

Not so fast!

• What if Apple changes processors again?

• What if Intel introduces a new vector library?

• What if some of your users are still on PowerPC?

• What if someone invents a better algorithm?

• What if, somehow, people are still using this in the year 2000?

OK, that last one might not be a problem anymore, but it does illustrate the point: you don’t know what’s going to happen to your application, to computer science, or to hardware in the future. That’s why hand-optimized code is a disaster waiting to happen.

I think you can see where I’m going with this. The Accelerate framework, as contradictory as it seems, is a high-level framework for low-level optimizations. That’s like hiring an army of mole people who dream in assembly and think in algorithms, and will continue to do so long after your application has shipped.

That means you can answer all the “what ifs” with “who cares.” You make one simple opti- mization and you’re done. No matter where your application ends up in time or space, it will have the best performance available for that particular computer. Even as silicon science pro- gresses, your application will get faster without your even being aware of it.

Here are some of the optimizations available in Accelerate:

• Image processing, including geometric and morphological transformations, histogram operations, and alpha compositing

• Digital signal processing on real and complex data types, including fast Fourier transforms, and vector-to-vector and vector-to-scalar operations

• A vectorized analog to the standard math library

• Linear algebra, including simultaneous sets of linear equations, eigenvalue and singular solution problems, and least-squares solutions for linear systems

• Routines that operate on matrices as if they were single variables

QuickTime Kit

At the heart of any modern operating system lies the ability to deal with multimedia. In case you’re unfamiliar with the term, multimedia is a mid-’90s buzzword meaning “the mixture of audio, video, and text; be it local, remote, or streaming.” Mac OS X has long been a frontrunner in multimedia. This is largely thanks to a very mature framework known as QuickTime, shown in Figure 24-5.

Figure 24-5.QuickTime as used by iTunes, QuickTime Player, and QTKit Movie View

CHAPTER 24MAC OS X DEVELOPMENT: THE APPLICATION FRAMEWORKS 427

Unfortunately, like much that is old, QuickTime had long been a holdout against the para- digm shift offered by Cocoa. This isn’t a technical problem, as Cocoa programmers are able to access other frameworks, just as non-Cocoa programmers are able to access Cocoa.

However, having to leave the comfort of Cocoa for the dark recesses of old-fashioned pro- cedural API is so much trouble, even for otherwise brilliant resources like QuickTime. Tiger finally corrected this with a brand new Cocoa interface to QuickTime, known by the euphonious nickname QTKit.

Here are some of the features of QTKit:

• Access to raw media data from local, remote, and streaming sources

• Object-oriented representations of media, tracks, and time ranges

• View subclass for displaying and controlling media

• Interface Builder object, which makes adding a full-featured media player to your applications a zero-code drag-and-drop operation

In addition, Leopard introduces QTCapture, which adds similar functionality to recording media. This includes the ability to control recording devices, such as the iSight camera now built into most Macs. For anyone interested in tapping the power of the iSight, I can attest firsthand:

QTCapture will save you thousands of lines of code.

NOTE For more information on QuickTime, check out Chapter 14.

Integration

Much of what makes the Mac such a compelling experience can be summed up in one word:

iLife. This suite of full-featured applications, included free with every new Mac (and the subject of Chapter 16) is not simply the sum of its parts. Rather, it’s the integration between those parts.

Make some music in GarageBand. Use it as a soundtrack in iMovie. Burn your movie to disc with iDVD. Then, tell the world with iWeb. This kind of integration, which is a concept from the very core of UNIX, extends throughout the operating system.

Your own applications can and should take advantage of this. Not only does this provide an excellent “Mac-like” experience to your customers, it saves you the time and trouble of imple- menting features that are already served quite well by existing applications.

In order to help you leverage these applications, Apple provides a great number frame- works, including several new to Leopard. Here is a quick tour of some of the most useful.

Address Book

As strange as it might seem to those of us who spend all our time with machines, many of our users maintain a network of an entirely different sort: friends, family, coworkers, and businesses.

To manage this pantheon of people, Apple provides an application called Address Book.

Rather than maintain separate lists for the people you get and receive mail from, call or text via your iPhone, and communicate with via iChat, everything is simply kept in Address Book.

Your applications can participate via the framework known, appropriate enough, as Address Book.

In addition to being able to access the contact information stored in Address Book, the framework provides the ability to search, edit, and add contacts. For any social aspects of your application requiring human interaction, the work is already done for you. Leopard provides a prebuilt People Picker, as shown in Figure 24-6.

Figure 24-6.Address Book’s People Picker view in Interface Builder

Finally, Address Book stores a special record known as a Me card, which contains a user’s own contact information. By accessing the Me card, you can spare your user the trouble of pro- viding their address, phone number, e-mail address, or home page, and simply present those fields for verification and, if necessary, correction.

NOTE For more information on Address Book, check out Chapter 11.

Automator

Automator gives users the power to create automated workflows using actions, services provided by applications on the system. Automator can be thought of as AppleScript with an easy, drag- and-drop interface. Your applications can provide actions as well, with a little help from Xcode’s Automator action template. Leopard takes that one further, and enables you to use Automator actions and workflows from within your application.

Moreover, the Automator framework even lets you embed Automator’s drag-and-drop interface in your own application, using custom view and controller subclasses, as shown in Fig- ure 24-7. From this interface, users can create standard Automator workflows. Or, if you prefer, you can create your own custom universe of components that just happen to borrow the con- venient and familiar workflow concept.

Figure 24-7.Automator view in Interface Builder

CHAPTER 24MAC OS X DEVELOPMENT: THE APPLICATION FRAMEWORKS 429

NOTE For more information on Automator and automation, see Chapter 23.

DotMac Kit

To those of us who’ve been online since the first IP addresses crawled out of the sea, the services of Apple’s .Mac subscription service are nothing new. E-mail, a home page, and a little space on a server somewhere are old hat. Still, .Mac manages to remain compelling, not with what it does, but how.

Normally, publishing things to the Web involves several steps and specialized file transfer programs. Using the WebDAV standard, the DotMac Kit embeds web services directly into appli- cations. A user’s .Mac account becomes less like a server and more like an online extension of their home folder.

Integrating with .Mac is a great way to add value for your users, and is probably the number-one feature that sets applications designed “for the Mac” apart from applications that are “Mac compatible.” Fortunately, the DotMac Kit, also known as the .Mac SDK, makes adding this feature almost as easy as using .Mac itself.

The DotMac Kit breaks all operations into transactions. This means checking credentials, making sure a user’s account is current, creating a directory, and moving files to and from the server are all encapsulated as transactions.

Transactions allow you to switch between synchronous and asynchronous modes as needed.

There are a few places where switching modes is handy, but it’s absolutely indispensable for debugging. There’s also a compatibility interface for the truly lazy, which mimics the methods used by Cocoa’s NSFileManagerclass. It doesn’t have the same flexibility as transactions, but for simple actions or quick prototyping, it’s quite convenient.

Calendar Store

As Address Book does for people, iCal does for events. Aside from the standard questions (What’s going on? Where? When? Who’s going to be there?), iCal events can include things like URLs, notes, and alarms: time-sensitive triggers that can do anything from popping up a reminder, running a script, and sending an e-mail. Using a colorful, easy-to-understand interface, iCal lets users manage all their calendar-related information in one place, as shown in Figure 24-8.

Again, just like with Address Book, your application can interact with iCal’s data using the Calendar Store framework. New in Leopard, Calendar Store frees your application (not to men- tion your users) from the tedium of dealing with the same information in multiple places.

Calendar Store does more than just accessing, editing, and creating events. It also does the following:

• Manages Leopard’s system-wide To Do list

• Notifies interested applications of any changes to the calendars

• Provides fast, flexible data-mining services using predicates: high-level, object-oriented queries used throughout Mac OS X

In fact, it’s better to think of Calendar Store as what it really is: a central database. iCal just happens to be a conveniently prebundled client. Indeed, Calendar Store is based on CalDAV, an open networking standard that lets your users connect with server-side collaboration software, regardless of platform.

It also means your applications calendaring features need no longer bind users to iCal. Any application can use Calendar Store. In fact, Leopard provides several examples of this kind of integration. The next time you get a piece of e-mail asking if you’re coming to the party on Wednesday, try clicking the text and watch iCal add that event, as if your host had sent you an iCal invitation.

Một phần của tài liệu Mac OS x leopard (Trang 447 - 473)

Tải bản đầy đủ (PDF)

(626 trang)