Cocoa • 1:13:47
Cocoa provides powerful object-oriented APIs for creating full-featured, next-generation desktop applications for Mac OS X. The Cocoa APIs include low-level utility, system interaction, internationalization, Internet, and platform-independence classes, as well as a rich set of user-interface widgets. In this introductory session, you'll get an overview and hands-on demonstration of the Cocoa features, APIs, and tools.
Speakers: Heather Hickman, Matt Henderson, Mike Ferris, Freddie Geier, Adrian Baerlocher, Matt Formica, Matt Rollefson
Unlisted on Apple Developer site
Transcript
This transcript was generated using Whisper, it has known transcription errors. We are working on an improved version.
Good afternoon. Welcome to session 300, Introduction to Cocoa. And this is a kickoff to an entire track dedicated to what I and many others in the room believe to be the best development platform for Mac OS X. We've got a lot to talk about in a short period of time.
Since this is the intro session, we are not going to have Q&A. We're going to run the full length of the session, let you get out of here. I know for the first day, probably some of you are tired from your travels out, so let's go ahead and get started.
My name is Heather Hickman. I'm the Cocoa evangelist in the Worldwide Developer Relations Organization, and I by far believe I've had the coolest job at Apple over the last year. That is working with you, developers, in evangelizing Cocoa. We're going to talk a little bit today about what Cocoa is. For many of you, this is going to be a bit of a review. I know you've probably been looking into Cocoa. You must be under a rock if you haven't heard what Cocoa is yet.
But, so just bear with me. We do have a few surprises in mind for you folk that are familiar already with Objective-C and memory management and Foundation and AppKit. But my assumption is that many of you have been so consumed in your development efforts and bringing your applications over from Mac OS 9 that you really haven't had a chance to take a closer look at Cocoa. And this week is going to be an amazing experience for you, so welcome.
So now a little bit about Cocoa. I'm going to go really quickly because we do have a lot to cover. It's a powerful, full-featured, easy-to-use object-oriented development environment for Mac OS X. And what that means is rapid development for you as a developer and increased productivity. I am seeing amazing things being done by leveraging the frameworks in the developer community right now. Students who are developing in Cocoa, seeing amazing work done. We probably all have some application on our desktop at this time that's written by someone under the age of 18 years old. It's absolutely amazing.
The point I'd like to drive home today, and I hope that you see, is that with a little bit of effort and a lot of creativity on your part, I really believe you could have the next killer application for Mac OS X by the end of the year. It sounds aggressive, but some of you are probably already leveraging the frameworks, seeing the benefits that Cocoa provides, and you can probably attest to this.
And I encourage each of you to talk to other developers here at the conference and get the point across as well. Cocoa rocks. Who thinks so? Oh, anyone seen this before? Mac OS X system architecture diagram. You can see what Cocoa is, peer to the other frameworks on the system, Java, Carbon.
So what you're going to learn today is a little bit about what makes Cocoa unique, what is this language called Objective-C, what is in the Foundation and AppKit frameworks, and then find out a little bit more about resources and opportunities for you to find out more about Cocoa.
Now, if you've been looking at the press releases about the show, there's been an exciting announcement as far as Cocoa development goes and the Code Warrior tools. And to talk more about that, please welcome to the stage lead technical engine—lead technical—no, what are you? You're a technical lead for Mac OS Tools, Matt Henderson from MetroWorks.
Hi. Thanks, Heather. So I'm just going to give you a quick demo. Well, where's my slides? Well, I had a slide, but I guess I've got a demo now. So, I hope many of you are already familiar with CodeWarrior, and I hope many of you are obviously here to become familiar with Cocoa.
And we're pleased to announce with the upcoming 8.0 release that CodeWarrior now supports Cocoa. We've worked very closely with the Apple Cocoa and Interface Builder team to achieve fairly straightforward integration between Interface Builder and CodeWarrior, so you can use CodeWarrior for your build system and Interface Builder to build your UI.
And I have here your standard CodeWarrior project that actually builds a simple Cocoa demo. And as you see, we have the usual mainmenu.nib. Double-click it. It opens the new version of Interface Builder from the April tool CD. So just to show you some of the integration, we have one image here already.
And we'll go add an image to the Code Warrior project. and just like that, it's in Interface Builder. So we can...
[Transcript missing]
In regular Cocoa development, then run it from Codeware. And we're building the Objective-C stuff and everything. You know, all we fix, we have. Well, that missed a slide.
Had the demo gone well, it would have run. We failed, and I should be doing push-ups. But nevertheless, the point is that Cocoa and Interface Builder have been integrated. I'm not sure why the demo goofed up. But try out our 8.0 release. You'll find that there are a lot of advantages for using Cocoa with Code Warrior, and it'll even further increase your productivity above and beyond what you do with Cocoa. Thank you very much.
So this is what Matt was going to say. Would you like to come up and speak to your slides? Yeah, come on up. Welcome Matt up to the stage. Okay, well, just a brief history. We actually, back in the early days of Rhapsody, we added Objective-C support to our compiler. And it's been sort of sitting there since then. It was either late 1997 or early 1998. So we haven't really marketed Cocoa support, even though technically we had all the compiler fundamentals to do it.
With CodeWarrior IDE 5.0 and CodeWarrior 8 that we're releasing later this month, we finally added long file name support. The biggest holdup for building Cocoa was that there were a few header files in Cocoa that had more than 31 character file names, which was a limitation of old Mac OS. So we fixed that.
And so now we can build Cocoa without any problems. And as I just tried to demonstrate was IDE 5.0 integrates with Interface Builder. And it actually does work. And I hope you all get the opportunity to try it out. And the demonstration. And then we have a number of events during the show. We have a MetroWorks lunch presentation tomorrow where we're talking a little bit about the same stuff.
We'll have a Birds of a Feather presentation tomorrow night where you have the opportunity to ask us about whatever you want, including Cocoa support. We'll have a lot of the CodeWarrior engineers there talking. Open all, not open all week, but open Tuesday and Wednesday, we'll have a CodeWarrior lounge where you can come and hang out. We'll have a pool table. And finally, there's a MetroWorks booth in the exhibit hall.
And with that, I'll give it back to Heather. Thank you very much. and all are going to get tired of seeing me, I'm sorry. Next, I'd like to welcome to the stage someone near and dear to my heart, Mr. Project Builder. Can I say that? I won't. Forget that I said that. Please welcome Mike Ferris.
is the, yeah, the mic is on. Okay, great. Hi. So, first I want to say that it's really great to see that CodeWarrior is finally supporting Cocoa, and actually, the demo was running, it's just that IB's connection lines were sitting on top of his running app window, so it was working.
I look forward, actually, to digging into the Code Warrior when it gets released and playing around a little bit with the Cocoa support. So, I'm actually not here today to tell you about how to use Project Builder to develop Cocoa applications. Instead, what I want to talk to you about today is the fact that Project Builder is a Cocoa application.
There'll be sessions later in the week, Wednesday. There's session 903, Exploring Project Builder, if you actually want to learn how to use our tools. Basically, let me start by giving a little bit of an overview of the structure of Project Builder. Project Builder is a pretty big system. It's made up of several different products. There's the application itself. There's probably about a half a dozen frameworks that we use, another 10 or 12 plug-in bundles, various command line tools, scripts, build system implementation scripts, all kinds of things.
We build this with Project Builder projects, and there are about seven of them that make up the entire IDE. The reason that there are seven is that we want to split our projects basically along layers. So we have a project that has all of the lower-level stuff, and then one that has all the UI stuff, and so on and so forth.
This gives you an idea of the magnitude of Project Builder. Under 300,000 lines of code in Project Builder. The reason that there are under 300,000 lines of code in Project Builder is because most of the code is in Cocoa. And that's really the point of what I want to say to you today, is that we are able to go as quickly with Project Builder in terms of adding new features and really moving it forward because we get to leverage all the stuff that is in Cocoa.
So, the title of this slide is meant to bring to your minds a couple of different quotes. There's, you know, on the subject of leverage, Archimedes, who said, give me a place to stand and I can move the world. And Sir Isaac Newton said, if I've seen farther than others, it's because I'm standing on the shoulders of giants. Now, actually, Brian Reed once said, in computer science, we stand on each other's feet.
And I think that Cocoa actually provides an exception to that rule. Cocoa is a giant, and you can stand on its shoulders. These are a few of the classes in Project Builder that we actually use a lot in... Sorry, a few of the classes in Cocoa that we use a lot in Project Builder. Not just use, but we actually subclass and extend these things in significant ways.
You know, we use window controllers all over the place. We use the document system both for project documents and for file documents for the file editor. We use the text system for our code editing. You know, we've added things like syntax coloring, auto-indentation, all kinds of things fairly easily to the Cocoa text system. We have a lot of extensions to the tables and outlines. We use split views. In fact, that sliding tab thing in Project Builder is actually a subclass of NS Split View.
We make a lot of use of the property list stuff and key value coding and other foundation facilities in Cocoa. So I guess the main point here is that we feel that we get a lot of leverage out of being on top of Cocoa. I've been doing Cocoa programming for about 13 or 14 years now, and I'm not sure that I would do programming at this point if I couldn't do it in Cocoa. So, that's really all I wanted to say.
Oh, you know what? Actually, there's one more thing I wanted to say. We do have several sessions if you do want to learn about Project Builder. There's a 903 Exploring Project Builder. There's also 908, which is a more advanced talk that focuses on delivery of your products. And then, actually, a related thing is AppleScript Studio. AppleScript Studio is very related to Project Builder, and Interface Builder is also very related to Cocoa. And if you haven't looked at it at all, I'd really urge you to go see this presentation because it's really cool.
So Project Builder is an example of a Cocoa application built specifically for you guys to develop in Cocoa. I thought it'd also be cool to have representation here from one of our engineering teams who actually develops applications for our customers. And this is one of the coolest applications on the system today. I'd like you to please welcome someone who graciously accepted to come and talk about their Cocoa development experiences, Senior Director of New Media Engineering, Freddie Geier.
Thanks for the introduction, Heather. And as you can hear, I am not a native English speaker, so excuse my really bad English accent. Let me share with you just a few words on the experience we made with Cocoa so far. After finishing iDVD1 in February 2001, the DVD engineering team, by the way, all traditional Macintosh developers at that time, reconceived their future development plans for the next major product releases on 10 for iDVD and DVD Studio Pro. And as a matter of fact, first of all, we thought carbonizing might be the simplest way.
But on the other hand, we had the feeling that this approach might be not the right way to go if you want to develop a future-oriented application. So we decided to survey an alternative. Of course, which is objective-oriented programming in Cocoa. After two weeks of critical investigations and believe me, hours and hours and sometimes nights of discussions how to proceed, it was clear to us that we don't want to compromise.
We took the challenge to learn a new language and started the development of our new project in the Cocoa environment. Only after seven months, we released iDVD, and hopefully you agree the app is truly succeeding. Living now with Cocoa for more than a year, we are still convinced that shifting into, for us, a new development model was a really smart decision. Today, on daily purpose, we take benefit of the dynamic binding, of much better memory management, event modeling, app kit, and other just native OS X capabilities. So my advice to you, go with Cocoa. Thanks.
and Matt Lange, and I'm going to introduce you to the Cocoa APIs. So, something else that I've done over the past year as Cocoa evangelist is be list mom to the Cocoa Dev discussion lists. And I don't know how many of you subscribe and post, but oftentimes, when I see something interesting come up, I would just email the person back off the list, of course, and ask for or solicit more feedback. And something I've heard over and over again from Cocoa developers
[Transcript missing]
So I'd like to welcome to the stage now Adrian Baerlocher from the QuickTime engineering team to speak about QuickTime and Cocoa development.
Hi, so I'm actually going to talk a little bit about QuickTime Broadcaster. This is a new application we're working on that lets you broadcast live events using Mac OS X and a DV camera. You can try it out for yourself. It comes installed with Jaguar Server. It's one of the CDs you'll receive here this week, or I guess two of the CDs you'll receive here. So QuickTime Broadcaster is a Cocoa application that uses many different components in QuickTime. Including the sequence grabber, standard compression, and broadcast APIs. We basically writ a set of Objective-C classes that sits on top of these QuickTime components.
As you can see from the screenshot, we're not using any of QuickTime's Carbon modal dialogues. They're all native Cocoa NS controls and views. And one of the great benefits of using Cocoa is that we were able to prototype many different user interfaces. For this app alone, we probably did like half a dozen.
And most of them were functional. And I can speak from personal experience that Cocoa is very easy to learn because basically six months ago, I didn't know Cocoa. And I learned it in that time and wrote this application. So it's a lot of fun. The classes are very consistent. The framework's very easy to extend. And the QuickTime team is very excited about Cocoa.
If you'd like to learn more about QuickTime and QuickTime in Cocoa, here's a few great sessions to consider. The State of QuickTime in 2002 is an overview of QuickTime over the past 10 years and where we're heading in the future. Building QuickTime-savvy apps discusses how to add QuickTime to your applications, whether they be Cocoa or Carbon.
Finally, if you want hands-on with a QuickTime engineer, there are hands-on sessions Tuesday to Friday, 1 to 4. These are great. You can bring your source code, your applications, and sit down with QuickTime engineers. I'll be there all of Thursday afternoon from 1 to 4. If you have any QuickTime and Cocoa questions, I'd be happy to answer them. Thanks.
Hopefully having Adrian join us is a sign of things to come. I welcome your feedback. If you would send it to me, my contact information will be on the screen a bit later, specific to Cocoa and QuickTime development. Now, I hope you enjoyed that parade of engineers talking about Cocoa development.
It was my intent just to have you realize that, in many instances, learning Objective-C and how to leverage the frameworks can be done in a short period of time. And it does take that time to get used to the idea of object-oriented programming and some of the classes that are available to you in the frameworks.
But after you've got that down, you can move pretty quickly to do some pretty amazing things on the system. So now to share more information, more of that "What is Objective-C? What are these frameworks?" and I'll come back and visit you a bit later, please welcome to the stage Cocoa DTS engineer, Matt Formica.
Thanks, Heather. So as Heather said, my name is Matthew Formica. I work in developer relations. I support Cocoa, as well as development tools. And if what we've seen so far today is perhaps the dessert portion of the presentation, now we'll get into some of the dinner, and then maybe we'll come back for some dessert at the end. So let's dive right in.
So, some of you may be sitting here today and you heard a little bit about Cocoa today, as well as having perhaps heard about Cocoa elsewhere, and you may be thinking, why Is Cocoa going to be overly simplistic? Is it going to be like perhaps other frameworks that maybe lock you into one way of doing things or force me to do things in a certain way? On the other hand, some of you may be sitting here today thinking, I've used other frameworks, and they all promise to reduce complexity in code, but I still find myself initializing line after line of this class, or that part of the framework, or that object, or hooking up these widgets. Isn't Cocoa going to be like that? Well, thankfully, I'm here today to tell you that it's neither.
Cocoa is certainly full-featured. This is, in fact, the class hierarchy, and if you can read any of the class names on there, you have better eyes than I do. Cocoa provides all the classes and hooks and callbacks you might need to customize things. But the nice thing is that, in general, you don't need to actually interact with most of these classes. They just do their job while you do your job.
This is the Cocoa class hierarchy as you might think about it in your head. It actually consists of two core frameworks: Foundation and AppKit. On the left, we have Foundation, which includes NSObject, which is the root object of the Cocoa class hierarchy. and foundation consists of what we generally think of as the non-GUI portion of Cocoa.
It includes such things as classes for dealing with values, collections, and strings, as well as classes for scripting and accessibility and working with the file system.
[Transcript missing]
The areas that are circled in red are the ones we'll actually focus in on today. Strings, collections, and OS services from Foundation, and user interface, text, and graphics from AppKit. But first, we have to deal with the question, which language to use.
So the Cocoa APIs themselves are actually provided in two languages, Objective-C and Java. Objective-C is a dynamic, highly object-oriented language that's time-tested technology and today is a part of the Free Software Foundation's standard GCC compiler distribution. Java is similar to Objective-C in its dynamic nature, and so Apple provides what's known as the Java Bridge, Java interfaces to the native Objective-C APIs.
One of the nice things about Objective-C is that it's a mere small superset of standard ANSI C. So you can take advantage of your existing C knowledge, as well as leverage existing C++ code you may have in your Cocoa programs, while taking advantage of Objective-C, where it really counts when using the native APIs.
So the question still remains, which language to use? And the answer is really, use the language that fits your needs. If there are critical Java libraries that you want to interface with, or you have an existing back-end Java engine that you want to take advantage of, you may find that programming Cocoa in Java is the way to go.
On the other hand, developers who don't have these requirements typically find that the lower runtime overhead and faster performance of Objective-C may get the language of choice. Apple supports both Objective-C and Java for Cocoa development. But we'll focus in on Objective-C today, and I'd like to take you on a brief walkthrough of the language.
I find, when talking with developers, that many of them feel like when they're first starting with Cocoa and learning Objective-C, that they're concerned about a ramp-up time to learn the language. It turns out that most developers can learn the language in only a few days. That's because it's a small superset of standard ANSI C, with some additional syntax to handle the dynamic object runtime. They often find when they're first starting that they think they have to do everything in a special, objective C way, when actually the standard C way of doing things is often the right way to go.
So the really unique thing about Objective-C is that it's a dynamic, has a dynamic runtime. And it actually takes advantage of weak typing as well. And this allows you to write powerful callbacks and handlers that take objects of generic type ID to refer to an object of any class. Then, using introspection, another feature of the language, we can actually query those objects at runtime to determine what their capabilities are and make decisions based on that information.
Here's what you've all been waiting for, the unique Objective-C syntax. It starts with a left bracket, and then the object that we're going to send a message to, and then the message name, followed by a closing bracket and a semicolon. So in this case, my object is the object we're sending a message to, and do something is the message we're going to send.
So what's really going on here? Well, it's actually a message being sent, not a function being called. At runtime, the object will receive this message and then decide which method to perform. It's almost like all methods are virtual. However, the information is actually cached by the system as well for performance.
Here's a couple more examples of parameters. So in the first case, we're passing one parameter, other obj, to the do with this colon message. So note that messages that include parameters end with colons. So the complete message is, do with this colon. It takes one parameter, other obj, and the message is being sent to my object.
In the second example, we actually have two parameters, and this can easily be extended to n parameters. And the interesting thing to note here is that we actually intersperse the message name with the parameters. So do with this colon and this colon is the complete message name. This can very much help make your code more readable. Never again do you have to look at a function call with 10 comma-separated numbers and sit there wondering what each number refers to or trying to match the prototype with the invocation.
Another thing to note here is the standard naming conventions for Cocoa methods. Note that the first word is not capitalized, but each word thereafter in the message name is capitalized. So, do with this colon and do with this and this colon are what's actually known as selectors. They are messages independent of any class, which you can actually send to any class. And often you will need to construct selectors when working in Objective-C and Cocoa for callbacks.
Here's what the class definition looks like. Note the pound import on the first line. Objective-C does support the standard #include directive used in C, but it has this additional include directive as well, which is what's typically used. And what it actually means is the same thing as a #include with an implicit #pragma once to tell the compiler that each header should only be included once. After that, the class definition itself starts with an at-interface and ends with an at-end. After the at interface comes the class name, then a colon, and then the class that we're subclassing from.
So in this case, my class is our class name, and we're subclassing from NSObject. After that comes an opening curly brace and any instance variables that we're declaring. Note that we always declare pointers to Objective-C objects. We end with an ending curly brace and follow this with any methods that we may have for this class.
And with something that may look curious to you if you don't already know Objective-C, is the leading plus sign or minus sign in front of each method. This indicates whether the method is a class method or an instance method, respectively. After the plus or minus sign comes the return type in parentheses, and then the method name along with any parameters.
Here's the class implementation. Begins with an at implementation and ends with an at end. There's a couple things I want to point out here. First, note that in the do-something method, we're sending messages to two objects we haven't talked about up to this point, namely self and super.
Self allows us to refer to ourselves within a method implementation, basically like Java's this object. Super, on the other hand, allows us to refer to a superclass's implementation of a method we've overridden when we want to take advantage of default functionality. This is very handy sometimes when you want to take advantage of the standard way of doing things and then add some little bit of delta functionality.
The other big point to note here is that you actually don't have to declare methods in the class definition to go ahead and implement them. Objective C doesn't suffer from the fragile base class problem to the same degree that C++ does, so we can present a clean interface for the class to users of the class, and then go ahead and implement any additional methods that we need on the back end.
So that actually covers the basics of the language, the real foundation of it all. But there are two other concepts which are not quite as foundational, but which we still encounter on a frequent basis when developing an Objective-C. And I don't have time to go into examples on them here today, but I did want to touch on them briefly.
The first item is categories. Now, categories actually allow you to add methods to existing classes. Now, that may not sound like anything special, but it's the way that we do this that's really cool, because you can actually add these new methods in your category in a different source file than the original implementation of the class. In fact, you don't have to have the source code to the original class at all to write a category on that class. As long as you have symbols to link against, you're good to go.
Now, you can add instance variables to a class with a category, but you can take advantage of existing instance variables in your category methods. And the neat thing is, at runtime, these methods are just as much a part of the class as any other method on the class is. So all your subclasses get to take advantage of these as well.
Categories are used very often in Cocoa. In fact, many of the methods you'll use every day are, in fact, implemented as categories in the frameworks. But why might you want to write a category in your application? Well, just think for a moment that you want to add a new string manipulation routine to, say, NSString.
One way you could do this would be to write a new function that takes an NSString as a parameter. But perhaps the more object-oriented way to do it would be to actually write a category on NSString where you add your new method. Then, all your NSStrings automatically get this behavior, as well as your subclasses.
Protocols are the other concept we want to talk about here today. Protocols allow you to declare methods not associated with a class, but which a class or classes can choose to implement to conform to the protocol, similar to Java's interfaces. If you claim to conform to a protocol and don't, you'll actually get an error at compile time.
So what are protocols good for? Well, protocols allow you to group objects by functionality when functionality and not class hierarchy is all you really care about. So, for example, you could combine this with weak typing to have a parameter to a method be declared as type ID, that is, an object of any type. But have it conform to a specific protocol to ensure that certain functionality is present at runtime.
And then there's this kind of thing in the middle that we call informal protocols. And they're categories, really. There's no compiler error if you don't conform to these informal protocols, but they do help group functionality. There's actually a Cocoa technique session later on this week where they'll go into this in more detail.
And that's actually the basics of the language. And hopefully if you squint a little bit, you'll be able to follow along with the Objective-C on the slides. But now I'd like to turn from the language Objective-C to the frameworks, Foundation and AppKit, and I'll start with a discussion of Foundation.
As I've said earlier, Foundation is actually what we think of as typically the non-GUI portion of Cocoa. And there are five things I'd like to talk about in relation to Foundation today. I'm going to talk about NSObject, which is the root object of the Cocoa class hierarchy. I'm going to talk about something that every application developer will need to deal with when working in Objective-C, which is memory management. Then I'm going to dive down into a few case studies of specific classes that you'll either use on a frequent basis or bump into from time to time when using Foundation.
So first, NSObject. NSObject provides base functionality that just about every other class in Cocoa will take advantage of. It helps bootstrap your objects and get them up and running. In fact, in Objective-C, there's no specific syntax for working with constructors, but NSObject does define two methods to help here, alloc and init.
Alec allocates memory for a new instance of an object at runtime, while Init initializes that object to default values. In your subclasses, typically you won't override ALEC, but you will either override INIT, write a more complex initializer like INIT with FUBAR, or both. Typically, the initializer that takes the most parameters is what's known as the default initializer.
And this object also provides some introspection capabilities for Cocoa. Methods like responds to selector, where you can actually ask an object at runtime if it knows how to deal with a certain message. And finally, NSObject has capabilities for asking objects what their class is, or for a string description of the contents of an object. This can be handy for debugging, among other things.
When it comes to memory management, Cocoa and Objective-C use reference counting. There are three main messages that you'll want to pay attention to. Retain adds a reference to an object. Release decrements it, and auto-release decrements it later, for some definition of later. And the rules are really quite simple. By convention, only creation methods like ALEC return retained objects, that is, objects with a retained count of one.
You can assume that all other methods will return objects that have not been retained. If you want the object to stick around, you need to retain it. On the other hand, when you're done with an object, you should call release to avoid leaking memory. When there are no more references to an object, that is, when its retain count drops to zero, the object will be automatically deallocated.
Here's a few examples. In the first line, you can see that we nest a call to Alec with a call to init with format. The alloc call gives us a new instance in memory of an NSString object, which gets passed right along to initWithFormat, which gives it some default values. initWithFormat returns the same new NSString object, which gets assigned to myString. So myString now has a retain count of 1. We then log out to standard out myString using the NSLOG function. And finally, to avoid memory leaking myString, we send it the release message, deallocating the object.
So let's turn from memory management to an example of one of the value classes that Foundation provides. This class is NSString. It's an opaque string class. It's used pretty much everywhere in the Cocoa frameworks. And one of its coolest features is that it provides what's known as toll-free bridging to core foundations CFStringRef type. That means that these objects are actually identical at runtime. You can directly cast from a CFStringRef to an NSString and vice versa, and pass them to methods that take one or the other.
NSString also provides lots of string manipulation routines for your convenience and is fully Unicode compliant. In your code, you'll want to use the at-quote construct to refer to a constant NSString, very similar to Core Foundation's CFSTR macro. And finally, like many of the other classes in Foundation, there's actually a mutable or changeable version of NSString, NSMutableString, that you'll want to use if you're changing the string as you go. This division between mutable and immutable was made to allow for optimizations to be done on the immutable version that would not have otherwise been possible.
Here's some NSString examples. Some string is first assigned to the string world! using the @quote construct. Then, we print out this string, along with some additional text, using NSLog, and its built-in printf-style format specifiers. %at refers to an NSString. And finally, we print out some more text on the length of the string using NSLOG and asking the string for its length.
NSArray is an example of one of the collection classes that Cocoa provides. And NSArray provides optimized expanding array support. And in addition, it's actually quite fast. It'll switch implementations on the fly at runtime based on your usage patterns. Some may see the fact that NSArray only takes NSObject subclasses as a limitation.
But besides the fact that you can wrap base types in value classes, one of NSArray's advantages is that you can have objects of any NSObject subclass all contained in the same NSArray. This can actually be quite powerful, because you can use, for example, an NSEnumerator and an NSArray to iterate through an NSArray that contains objects of lots of different classes, and then call the same message on each object.
The other nice thing about NSArrays is they too provide various manipulation routines. For example, combining arrays or comparing arrays. And NSArrays retain the objects that you add to them so that you don't have to. And finally, like NSString, you'll want to use the mutable version of NSArray, NSMutableArray, if you're changing the array as you go.
And thirdly, we come to an example of one of the OS services that Foundation provides. And this class is NSTask. It allows you to launch other processes to do work for you. And then you can interact with them via Standard In, Standard Out, and Standard Air, and the NSPipe class.
NSTask is commonly used to wrap command-line tools or shell scripts in a Cocoa GUI. And often what you'll do is take your favorite command line application and put a Cocoa interface on it to increase its user-friendliness. And this can be, at times, the fastest way to port or get an application up and running on the platform. Let's take a look at how you might set up an NS task. First, you can see that we're calling alloc and init to create a new instance of an NS task and then initialize it to default values.
Then, we send it the set launch path message to actually tell it what application we want it to launch. And after this, we tell it what arguments we want to pass to this task, and those arguments are contained in an NSArray. Here we're passing just a couple of flags to LS, as well as the director we want to list. Finally, we allocate and init a new NSPipe object and set it to be the standard output of the task so that we can get the results, and then we launch the task.
So that's a quick flyby of Foundation. There's obviously a lot more there, but there are lots of other sessions this week where you can find out more. I want to turn now to AppKit, which is the GUI portion of Cocoa. And once again, there's five things I'd like to talk about.
The first is Model-View-Controller, often abbreviated MVC, which is a standard design pattern leveraged by Cocoa. Then, I'd like to talk a little bit about some of the application-level services that AppKit provides for you. And we'll mention briefly the text and drawing subsystems. And finally, we'll get to a discussion of the event system in Cocoa, controls, and conclude with a brief demo.
So, you don't actually have to use Model-View-Controller in your applications, but it does really help and is leveraged by Cocoa to help break up your application into the parts that do the work, the parts that display the results, and the parts that interact between the two. So the model is the first part. This is where your back-end data is stored, and this is the part that actually gets the job done in your application. Typically, in a cross-platform application, the model is the part that goes most easily from platform to platform.
And the view part of your application is actually the antithesis of this. These are the buttons and widgets and sliders that the user interacts with. But the view parts of your application don't actually need to know very much about how to store the data or how to operate on the data.
And then there's the controller part of your application. This is the part that talks between the two. It serves up data from the model and displays it, hands it off to the view, and then it parses responses from the user in the view and hands them off to the model. This can help enhance code factorization, encapsulization, and reuse in your applications. We'll come back to some examples of Model-View-Controller in action in a little bit.
So, when it comes to handling application-level services, you actually want to use NSApplication, of all things. And you'll interact with NSApplication through the global NSApp object defined for you in your applications. NSApp does a lot of work for you. It will actually, upon application launch, set up the menu bar, load the main nib, which is your application's user interface file, handle the dock menu, and lots more for you. So you'll want to message NSApp when you want to do application-level tasks.
For example, you can ask NSApp if your application is hidden. Or, on the other hand, you could set your application's icon image in the dock to provide feedback to the user. Beyond NS application, however, AppKit provides a slew of functionality in a lot of different classes. And we don't have time to go into all the gory details today. But I did want to touch briefly upon perhaps what is a whole solar system of classes in AppKit, which is the Cocoa Tech System.
The nice thing is that most developers never have to see or work with all these classes because they're wrapped up in one complete international drag-and-drop widget, NSTextView. NS TextView does a ton of stuff right out of the box. Whether it's fonts, images, spell-checking, the kitchen sink, you name it, it's pretty much in there in some sort of standard, reasonable, default behavior right out of the box. But it is a front-end for a bunch of interlocking text classes, and so you can do things like syntax highlighting or some of the other things that Project Builder takes advantage of. You can write a complete word processor using the Cocoa text system.
There's a session later this week on Cocoa Text, which I encourage you to go pay attention to if you're interested. and turning from text to drawing, in addition to a complete NS view drawing architecture, there are drawing methods scattered throughout the Cocoa class hierarchy. Furthermore, core graphics calls can also be used, and there's a Cocoa drawing session specifically to talk about these later this week.
So now we come to the Cocoa Event System. When it comes to events in Cocoa, NSApplication will handle your event loop for you. This is actually very similar to how runApplication event loop does on the Carbon side. So how does this work? So, you have a GUI application.
You have a window on the screen with some widgets in it, say, a text field, a button, a slider. And at runtime, one of those widgets will be determined to be what's called the first responder. That is, as NS events get handled and come in through the system, The first responder is the widget that will get the first chance to respond to those events. So, oftentimes, perhaps, the text field in your window will be the first responder, so that key press events will go to that text field.
However, as your application is running, the first responder can and will change on the fly automatically. Say, for instance, the user clicks on a different text field. Well, that new text field will then become the first responder, so that all key press events will now go to that text field.
So what if a particular widget doesn't know how to respond to a given event? Well, if this happens, the event is actually sent up the responder chain until an object is found that responds to the event. This is actually quite powerful. In fact, the first responder and the responder chain are powerful not only because they're very dynamic, but because of a couple of other paradigms, namely target action and targeting the first responder, which allow the responder chain to actually dynamically reconfigure itself on the fly based on user interaction. So, to understand how this works, we first have to talk about controls and target action, and then we'll come back to talking about the first responder.
Controls and other related classes typically have two key parts. They have an action and a target. The action is the message that will be sent when the control is actually triggered. Meanwhile, the target is the object to which that action message will be sent. Take NSButton, for example. You could, for example, have an NSButton in your application wired up to some code you have that, say, is a document that knows how to print itself. Thus, when you press that button, it can send the print action message to the document target.
NS Menu Items work this way as well. When you select a menu item in a Cocoa application, it will actually send an action message to a given target that it's been wired up to. This is a key point. These action messages and targets are actually wired up in Interface Builder. There's no code that you need to write to hook up your widgets to each other. I'll demo this shortly.
So if that's what controls are, let's come back to the first responder. So we've talked about target inaction, but the target can actually be determined on the fly. And this can happen if you hook up the target in Interface Builder to be the first responder. Then the action message will be sent to whoever the first responder happens to be at a given point in your application.
This is actually quite powerful. Cut, copy, and paste work this way in Cocoa applications. They actually will send the cut, copy, or paste action message to the first responder, whatever widget that happens to be at that point. So if this text field is the first responder, cut, copy, and paste will operate on it. If a different one is the first responder, cut, copy, and paste will operate on that one.
But what if the first responder is something that doesn't know how to respond at cut, copy, and paste? Well, this is handled for you automatically as well. If you recall, we talked about introspection capabilities a little bit earlier. Well, menu items can actually auto-enable and disable themselves on the fly at runtime. If a given first responder doesn't know how to respond to a given action message, Cut, Copy, and Paste will automatically realize that and disable themselves.
So now we'll move on from the event system to something that's perhaps a more sophisticated widget in Cocoa, and that is NS TableView, something similar to Carbon's data browser. NS Table View is actually a view in the Model View Controller paradigm. So it doesn't store any of the data that it displays. That's up to you. You need to write an object that conforms to the NS Table data source informal protocol.
You write the model. And this is really handy. This is a really handy separation because the table view doesn't have to know anything about what your data looks like, really. And you, on the other hand, don't really have to know how to draw a table view. You just write the part that you can do best.
So, what's this about writing an NS table data source protocol? How many methods do we have to implement to get this to work? Well, if you just have a display-only table, there's only two methods to deal with. Number of rows in table view is the first method, and you basically just have to respond with how many rows this table has. The second method is table view object value for table column row. And this actually gives you a column in row, and you need to take a look at your model and respond with whatever data should go in a particular cell in the table view to be displayed.
That's all well and good if you have a display-only table. But if you want the user to actually be able to enter data in your table, you've got to do more. How much more? Only one more method. This method is table view set object value for table column row, where given an object value in a column in a row, you get a chance to stuff this back into your model.
But how does the table view actually know whether you've implemented this method or not? Well, once again, it uses introspection. It will actually query your object at runtime, ask it if it implements this method, and if it does, it will be called. If not, it won't, and the table view will automatically enable or disable user editing based on whether you have this method.
So now to demo in this table view on some of the other concepts we've talked about today, I'd like to invite Heather Hickman to come back on stage to help me with a brief demo. This demo is called MP3 Player. It's a small little Cocoa app, only about 50 lines of code, that actually calls through to an NS task.
That's actually executing MPG-123, an open-source MP3 player that you can download for yourself off of freshmeat.net. So let's open the Project Builder project. What we'll do first is take a look at the Nib, which is this app's user interface file, and see what the interface looks like for MP3 player.
There's two main parts of the interface here. First of all, we have a basic window. Inside the window, we have a table view where we actually display MP3s that we've dragged in. This table view is actually a custom table view subclass that knows how to play MP3s. The other user-interface element we have here is a basic menu bar. It has all the standard menu elements we might expect. So if that's the interface, let's go run the app and see how it works right now.
So, right out of the box, we get a lot of Cocoa functionality for free. The window just easily knows how to resize itself. Oops, there's a button over there. I know. And... I didn't see that. menus just work. We even get a default about box that pulls information out of the application to display. But we're not really interested in the user interface. We're writing the application to play music. So let's drag in some MP3s. So it just parses that, drops them off on the table, and then to play one, we can just double-click on it.
You'll notice that actually we are calling through to MPG-123 because the console in the back gives us standard out and displays the MPG-123 output. Okay, so let's take a look at a little bit of the code here. First of all, we'll take a look at My Controller. And this class is actually, for such a small app, a combination of the model and the controller. And there's a few lines I want to take a look at.
First of all is this set double action line. Our table view is represented in our code by the song table object. And what we're doing here is telling it that when we double-click a particular row, we want it to call the play song method to actually start playing an MP3.
The other thing we'll look at here in the code are the two NS table data source protocol methods that we need to power this table. The first one is number of rows in table view. And we can see here that we store our MP3s in a basic NSArray called songs. And so to find out how many rows this table view should have, we just call count.
In the second method, we have TableView object value for table column row. A long name, but hopefully it makes the code easier to read down the road. And here, it's quite simple as well. Given a particular column and row, we would just return the appropriate item from our songs array.
So if that's what's driving the array, what's actually playing the songs? Well, it's the MyTableView table view subclass. There's two methods here, playSong and stopPlaying. First thing we do is we ask if we actually are already playing a song, because we don't want to have two songs playing at the same time. We tell the song to stop playing.
After that, we have some code to actually calculate a path inside our application package that points to MPG123. Then we alloc and init a new NSTask object, set its launch path to be the MP3 player, and then set whatever arguments we want. In this case, just a path to the MP3 we want to play. After doing a little more initialization, we launch the task, playing the song. Stop playing is actually even easier. If we're actually playing a song, we just terminate the task and then release it to avoid leaking memory.
So that's the real core guts of the code that's actually playing the music here. But there's a flaw in our user interface. What if we get a telephone call and need to stop the song? Well, we actually can't do that in our interface here, short of quitting the application. Wouldn't it be nice if we actually had a button in the window that we could press to stop playing the song, and another button to start playing songs? Well, Interface Builder will help us with that.
Interface Builder provides a complete palette set for all the different widgets that Cocoa provides, everything from buttons and sliders to drawers and text views. But what we want are buttons. So, we'll drag in a couple of buttons. Notice as we drag them in, these blue lines showing up in our view. These are the Aqua guidelines. It's Interface Builder helping you write your applications in conformance with the Aqua interface guidelines.
Now that we have both buttons in place, we'll change one of them to say "play" and the other to say "stop." So that's great, but changing text on buttons doesn't actually build in functionality. To do that, we need to wire up these controls to their targets and actions. So what's involved there? Well, it basically just involves control dragging from the widget to the target. Our target in this case is the table view that knows how to play songs, and the action method we're going to hook up play to is the play song action method.
Then we'll hook up the stop playing button to the stop playing action message. will then save this in Interface Builder, go back to Project Builder, and rebuild the project. Okay, we'll drag in some songs again. And we now find that we can actually play them by hitting the play button. We can stop playing them by hitting the stop button. Thanks, Heather.
Did you get all that? So for those of you that are brand new to Cocoa, I wanted to take this opportunity to let you know that some time next week, on the ADC site, a little bit earlier in the conference, in fact yesterday, we had an introduction to Cocoa Early Bird session, which is a four hour hands on session that's very interactive and you're able to begin an application and actually have that evolve within the four hours. And what we did is we videoed that session.
We are doing some post production work on it. We're going to divide it into four segments and we're going to re-deliver it streaming off of the ADC site next week along with the files and the exercises included in the session. So you will receive an email through your ADC membership to let you know when that's available and we're interested in seeing your feedback on that. So if you didn't catch it all here today, it's okay.
Now that being said, documentation, documentation, documentation. This is another topic that I've heard a lot about as the Cocoa evangelist. And I can understand that documentation makes it a lot easier for you to do your job. We've got some exciting announcements here today. I'd like to welcome to the stage, manager in the Cocoa Tech Pubs group, Matt Rollefsson.
Thank you, Heather. So I wanted to just say a few words about documentation because, as we all know, sessions like this are great for giving you an overview and giving you an idea of how things work, which is essential to understanding how to use the technology. But when you get down to brass tacks and have to actually write code, you need to know what it looks like, exactly what every method does, and how to call it.
Oops. Except it goes backwards. So the first thing I wanted to say is that there is a lot of content for you. We've got a lot of documentation, chips on the system. It's accessible for you directly on your system. If you don't have a connection to the Internet, you can still look at your documentation. As of the developer tools CD, so the April developers tools CD that you received today, we are in fact reference API complete for Mac OS X 10.1. So, no more description forthcomings in the reference API.
We will be working hard over the coming weeks to make that true for the Jaguar release as well. On the seed, you'll find that there are some description forthcomings that are back as the engineers have been introducing new API. A lot of the stuff has been documented in the official documentation. Also, there are release notes about much of the new information. Rest assured, by the time Jaguar actually ships, we will include all of the new APIs as part of the documentation in the developer tools that ships with Jaguar.
There's also a good deal of conceptual material that's available from the website and also on your CD as part of the programming topics. It is not complete, but there's a lot there. It gives you good orientation to how the system is designed, how it's meant to be used.
And the good news there is that we're constantly working on that, and there's more on the way. So we'll be going through that conceptual material, expanding it, putting out a lot more material for you, and your feedback is definitely appreciated. If there are specific areas that you found the material that we have out there is not quite sufficient to get your job done, please let us know at the TechPubs feedback session later this week or by email so that we can best understand how to focus our efforts to help you get your job done.
As I said, documentation does ship on your system. So to make it more accessible to you and make it easier to use the documentation, we've integrated it with Project Builder. And the documentation, when you do a definition search in Project Builder, if there's documentation available, there's a little book icon that shows up.
Click on that book icon, and you have access to the doc right there from within Project Builder. Without having to switch around to some other system, having to go out to a browser on the web, or go to some other application, you can access your documentation directly. You can also get to documentation from Project Builder's class browser. And with Jaguar, the Project Builder team has introduced the ability to do general text searches of the documentation. So you can look through... Search through the conceptual material right on your system without leaving Project Builder.
So, that's pretty much what we've got in Mac OS X. Yes, Heather? Heather Not so soon. So, pardon me. I'm going to take this opportunity to ask Raleigh about something that I've been hearing about over the last year, specific to documentation. And what's happened with all that feedback about printed API reference for Cocoa? Matt Printed API reference? Heather Printed API reference, yeah. Matt Do you have any idea how many pages, how many thousands of pages that is? Heather Yeah, but, I mean, and I know the work that you've been doing in the, you know, getting rid of the description forthcomings, that's a great thing, right? That's an amazing thing.
But in addition to that, developers like printed API reference. They like to be able to highlight things. They like to be able to dog-ear things. They like that. You're sure? I'm positive. It doesn't just take up space on your desk and accumulate dust. Well, it does. It does.
It takes up quite a bit of space on the desk, but you know, I get a workout, putting them back up on the shelf, and they make me look smart when I have that whole API reference. So you really want this? I really want it. I really want it.
So she says you guys really want this. Do you really want printed API reference? Okay, okay, I guess we can do that. Heather Whoa! Matt So, it's my pleasure to announce that we will, in fact, have hard copy API reference for Cocoa, Foundation and AppKit, both Java and Objective-C, available this summer in print-on-demand online.
So, look for an ADC announcement of this sometime this summer when we've got Jaguar Final, all of the APIs complete for it, and you'll have these big old homes on your desk that you can access. Heather Woo! I had no idea that he was going to announce that whatsoever. No idea.
Okay, so we've shared a lot of information today. Compared to last year, we have tons of more information to provide to you over the course of the week. You all have it in your schedule, but this is just a roadmap. Please don't miss the 9 o'clock session tomorrow. We're going to go into what's new in the Cocoa frameworks.
And then from then on, API techniques, scripting, controls and accessibility, it goes on and on and on. I'm very interested in speaking with you on Friday at 5 o'clock. I know, I know, the last session of the conference. But that way, I'm only going to get the really important feedback. I had that in mind when I planned this. So 5 o'clock on Friday, feedback forum for Cocoa.
This is me, H. Hickman, at Apple.com. If you don't catch me in the hall during the conference, please feel free to send me email. I will not be reading it this week, but shortly after, I will get back in touch with you. Sometimes, that's a bad thing. And then for more information, I'm very excited.
If you've picked up your bags and looked at your coupons, you see that everyone that's attending the conference is getting from O'Reilly the new building Cocoa applications, a step-by-step guide. I think that is absolutely amazing. Please go pick it up, share it with people when you go back to your offices, have them ordered off the O'Reilly site. Great stuff.
Heather In addition to the Cocoa developer documentation, we also offer customer training. We have an incredible group in our training organization that's helped me extensively over the past year, and I appreciate their support. They've done amazing work. They're training our internal engineers. If you and your company are interested in training, please go to train.apple.com where you can get more information. Have a great week!