---
title: WWDC2004 Session 404
framework: wwdc
role: article
path: wwdc/wwdc2004-404
---

# WWDC2004 Session 404

## Transcript

Kind: captions Language: en good morning ladies and gentlemen at this time would you please welcome Matthew Formica cocoa and developer tool evangelist good morning and welcome to you all this is session for four fundamental of cocoa my name is Matthew Formica as was said I'm the cocoa evangelist tiered Apple I would love to throughout the week and do the coming weeks get your thoughts ideas and comments on Coco you can email me at em Formica apple com after yesterday's keynote sessions today and for the remainder of the week we're going to dive down into some of the technologies that make mac OS 10 the great platform that it is one of those is a technologies is Coco apples object-oriented rapid application development framework and here to talk to us about that today is a Leo sir who's been involved with cocoa and architecting cocoa for over 15 years he really knows his stuff so please join me in giving a warm welcome to all yo as your manager the core team well I'm glad you found your way to session 404 fundamentals of cocoa I'm a loser manager of the cocoa framework scheme so we have a lot of material to cover today and just to give you an overview of what we're going to talk about quickly cover what's cocoa then give you a quick overview of objective c which is the background you need to see some of our demos and the rest of the talk the bulk of the talk will be demos where we going to see the wonder of cocoa we're going to do demos write some code and get some applications running right in front of your eyes so you can see what cocoa is all about so first of all what is cocoa it's an object-oriented api's for doing a full-featured application development on Mac OS 10 when we don't think of cocoa we think of frameworks now framework Mac os10 frameworks are basically just libraries you're probably familiar with frameworks there's the carbon frame or a quick time frame work etc frameworks are just libraries which have come with bundled with resources headers frameworks also in the traditional Mac OS 9 definition like Mac App include in programming environment where the application doesn't run the event loop it's not actively running the event loop but is instead it's getting callbacks from the framework environment and Coco certainly fits that definition of framework where it is giving callbacks to your application and we'll see that in action today so the two frameworks that makeup Coco decor Coco our foundation and application kit and there are many other frameworks that participate in making up what's Coco and there's languages Objective C and Java object to see is the native language of cocoa what cocoa is written in we'll see a little bit of objective-c in a while and Java is also is dynamic languages objective-c and it works well with cocoa and tools xcode an interface builder you've seen probably both of them yesterday in the keynote and other sessions and we'll see those today as well and how they're how they are crucial in developing cocoa applications so let's not talk about the two frameworks foundation and application kit foundation is the core cocoa framework for non you I functionality if you're writing an application which has no graphics user interface no menus windows etc you will use the foundation framework foundation includes the root class which is nsobject almost all cocoa classes are derived from nsobject it includes operating system facilities so you don't have to drop down into you next layer if you don't want to you can use the classes and foundation it's got classes for internationalisation both note here is NS string which is a class you will encounter a lot it's the class that represents character strings in cocoa we have classes collection classes and foundation classes for scripting making both you're both making your applications scriptable and being able to drive scripting for other applications and also classes for XML processing and web access some of these were added in Panther and new ones are also coming in and tiger and there's a rich set of classes now in foundation for letting you do XML and web related stuff and much more app kit also known as the application kit is the Coco framework for creating applications with user interfaces it's got classes for drawing and event handling and we'll see those today it's got standard controls a lot of controls you've seen the Aqua interface buttons sliders etc again will CDs today standard dialogues safe panels color panels classes for accessibility image found media handling at rich document architecture that lets you create multiple document applications a powerful set of texts classes to let you create a powerful international and rich typography apps that feature text and again much more so the strengths of cocoa as I said earlier Coco's full-featured and powerful which means it's got features that lets you create applications that you can ship on Mac OS 10 as you know as you probably know most of the applications that ship with mac OS 10 our cocoa and they're also a lot of third-party powerful applications out there so it lets you create full-featured applications there's not just toy yet it's also consistent and easy to use the API for Coco are it's not a very huge API and consistent renamed there's also a few design patterns that we can use over and over so once you learn a little bit of cocoa once you start getting into some aspect of cocoa you start being able to predict what other cocoa functionality looks like in addition you're able to develop your own functionality that's consistent with what Coco delivers which makes everything fit together much better Coco is also customizable and extensible because it's object-oriented if we didn't provide the exact functionality you need you can usually subclass and extend the classes we gave you to do what you want to do it's also tuned for Mac OS 10 Coco is not some layer on top of some layer on top of some layer held together with some week object-oriented stuff it's a powerful object oriented environment that plugs well into Mac os10 takes advantage of Mac OS 10 strengths and various other libraries available in mac OS Kenya UNIX ports etc and Coco plays well with others Coco is written Objective C Objective C as we'll see in a min is primarily a sea-based environment and so with cocoa you can use any C or C++ or UNIX library that's available to you on the system in addition a lot of open source packages a lot of other UNIX packages out there can be used from cocoa applications with absolutely no difficulty whatsoever there's one thing we like to say about cocoa and that simple things are simple and complex things are possible the things that most applications should be doing things that are straightforward and simple it's just you can go ahead and do it in to almost no work or a few lines of code but if you want to do unique things in your application things that are out of the ordinary things that will distinguish your application and cocoa makes that possible as well okay so let's just do a quick demo of your first application of the application because it's not going to involve much code or any code so you've seen Xcode i'm going to go ahead and create a new project when you say new project you get a bunch of choice is one of them being cocoa application there's also other choices for document based apps etc and we'll give it a name my app now when you create an application cocoa it gives you the few files to get started you'll notice that one of those files is main em it's basically a boilerplate plate just cause the function to get things started we almost never modify this file another file of interest is the nib file main menu nib this is the file that contains your applications user interface very small apps will have one of these more sophisticated apps will typically have two or three dozens maybe many dozens of interface files and these are created an interface builder and this is very defined your user interface i'm going to double click on this now to open it in interface builder you notice that integrates builder launches you have a design window you have a window that represents your menu and you also down here have your document window which represents the various objects that are in your interface file this is your palette window where you have various standard controls that come out of the box and you can also add your own custom controls here as well for instance one thing we can do is drag out a text is the text object notice that is you're placing it down interface builder is helping you place it properly although I've spoken to it but let me drag it down you bring up the info panel the inspector to to modify the characteristics of widgets you should use drag from here for instance in the case of the text object you can choose the color you can change its border you can say that undo is allowed you can choose various other options here I don't know if you can read that I'll show you some others for instance I can drag out a slider with a slider you can choose its minimum maximum etc you know things you might expect now back to our text view if you look at this tab here you see there's connections outlets target actions will talk about that in a few minutes there's a size inspector which lets you change very sizing behaviors if you choose the internal Springs that means a text object will size is the windows sizes and let's also drag out a button now typically in interface builder one way you do your development is to put your UI together and you go ahead and say test interface when you do that I'm interface builder starts running your application using the interface you created now note that the slider is alive it's not doing much the button is alive it's not doing much and in fact the text object is alive and it even has features like a font panel I can change the font here and i can even you know it even has undo because earlier I said that undo should be allowed in this text object I can resize the window notice that the text object resizes and these buttons these space relative to the lower left corner so typically you use the test interface to test your interface if you have objects in the palace now if you develop custom objects that are not yet in the palette window here then you can't test do them in test interface you typically build your application to take your application to the next level of course you can always build your own palette objects put them here and that way you can test your interface in its face builder okay so one other thing to note about nip files is when we did this we generated the nib file note that the nib file has no source code in it it just saves archives the objects that we're using here the window the slider the button and it archives of connections between them as we'll see in a few minutes so there's no source code generated okay now let's go back to slide so we can play some with source code thank you sweet okay so in that demo we saw Windows slider button text view on panel are some of the objects we saw as you see here a standard theme and cocoa objects is the prefix NX which lets you recognize that these are standard app kid objects now let's talk a little bit about objective-c so we can start writing some code objective-c as I said earlier is a small superset of C it's super set of a sec it's got some additional syntax and a few additional types let's go back okay it's got a dynamic object runtime by which I mean metadata that goes with the objects and introspection facilities that allows to make this that allows making decisions at runtime about the objects and we'll see the power of that in our demos it's also a single inheritance object-oriented language in objective-c here is how you define a method a method is of course an entry point into a class here we have a method called set width colon height colon one thing to note here is that the name set with colon height coldness split such that every each parameter the W and the H have a name in front of it so set with colon height the full name of the messages set with colon hi colon but the name is split which of course for longer method names with you know four or five arguments makes it a lot easier to read here you know this is how you define a name what it seems to be doing is taking those parameters assigning them to maybe instance variables to invoke a method which we also say sending a message you use the braces so here we're sending a message to an object my box the set with colon height colon method and in the line below you see a nested method call where we first making a call to array object at index which presumably returns a box or some object and then we send that in turn set with colon high school and you can nest these method expressions just like you can nest function expression one other thing is you can refer to a method and this goes along with the dynamic object runtime there is a type SEL sell short for selector which allows you to refer in this case to the method for instance set with colon high skoland by using this app selector syntax once you do that you have a variable which represents this method name and then you can apply to the different objects note that this is not a function pointer because depending on what object is set to it will invoke different pieces of code a little more objective c you can refer to an object by either saying box star or an ID the difference here is that these are compiler these help the compiler determine what type of methods are valid when sent to that object box star indicates an instance of a box class ID indicates any object if you refer to this meaning yourself in the context of an object with self and finally of note is constant strings as I mentioned earlier we have the end of string class the we have a construct for creating constant strings in your code and that's at quote here you see the console string as quote hello world being assigned to a variable of type in a stream okay now that we're armed with some object to see knowledge let's go ahead and write some code and the first thing I want to do is do some custom drawing to do custom drawing you use a class called NS view it's an app to class it's an abstract class meaning you almost never use it as is but you subclass it and you would subclass it to do custom drawing and you can also subclasses to do event handling drag and drop and plenty of other stuff it's a abstract class with a lot of functionality to do custom drawing you override this method called draw rect to do your custom drawing in the context of a view you would use these classes in anastasiya pass class that represents paths in s color which represents colors it's actually a fairly rich class it's not just your garden-variety RGB where the cone also represents CMYK patterns and the whole other set of color spaces the NS image class which represents images and note that you can also use the full functionality given to you by quartz quartz is a sea-based API it presents a PDF based drawing drawing environment and Coco uses courts so the drawing and mines are compatible and quartz is written in C so the api's are in c so from coco you can call them to courts all you want so in cases where you can't call into the NS functions for some reason course is also available ok so let's do a demo of custom drawing ok so now we're back in Xcode the thing I'm going to do now is I'm going to add a new class a subclass of view because as I said we need to subclass view we're going to say new file and note that there's some pre-prepared entries here for you Objective C class objective-c document subclass so on view is one of them will choose that this is just a little convenience you know you can just choose the basic class and do some of the things that does for you but we'll choose nfcu subclass will call it docks you will create dr. H which you'll see in a minute and we'll add it to our target as you see doc view has been added here to our project oops okay hide that area now we're looking at dr. H which describes the interface to your application for this demo I want to edit the dot view implementation file so I'm going to click this button here go to counterpart which switches to the dot m file which is where your class definition where your methods sit so if we look at dots um here are the methods it is a convenience again only as a convenience to generate the scores source code for us and init method thinking grant one initialize in a draw method thinking we might want to draw so for now let's just look at our draw method and let's just customize it now during this demo I'm going to be I'm going to be a taking advantage of a demo assistant I have hidden in the computer here and as i type keys it will type for me let me show you there's a comment and there's three lines of codes it's magically appear these treats at lines of codes I ask self that's the NS view for the balance ballinger presents the area of the view and that's assigned to this balance variable which is NS wrecked and as direct is nothing magical it's just a see structure that represents a rectangle then we do a nested method call here method invocation where I ask in this color class for the white color that returns an instance of color which represents white and I tell us to set so that sets the current graphics context color to white and I call a function Rexville to fill the balance with white so that clears the view to white note that I could have used busy a path here but I'm using this function Rexville to show you Coco is not limited just to classes and methods Coco also has some functions who are appropriate so this clears our view now let's go ahead and draw it draw something interesting which in this case is a dot for that I will first to the comments and then create a wreck that represents the bounds of the dot whoops now we'll set the blue color just like up here and then now I will use a busy a pass creating a busy a path that represents an oval with this rectangle in this case it's a circle because the rectangles are square and then i will tell it to fill so this will create a circle and then fill it with the color we created here so it's pretty up this a little bit let's save and now I'm going to hit build and run command are okay oh I forgot one very crucial thing let's go back to our demo here the thing I forgot is to go into our interface builder and actually create the UI for my application interface builder I want to go ahead and get rid of these three things which we used earlier and instead I'm going to be using under the containers tab a custom view again let's follow I these guidelines draw our custom view here let's make it sighs centrally just like we did with the text view and the one more thing we're going to do now is tell interface builder that this custom view is of type dot view and to do that under the classes in the document window here under classes I can either go ahead and subclasses NS view I can hit the right mouse button or control mouse here to do that another thing I can do is do read files and then ID will allow me to choose among the various header files I have in which case i will read da coh which is the header file I just created the moment I do that interface builder now knows that there's a subclass of view called dot view I hope you can see that down there so I can come to my custom view here and in the inspector I can specify its class note that the various NS classes are listed here already I want it to be a subclass of I want to be an instance of that view so I do that I save here I hide interface builder go into Xcode and let's run as you see we now have our window with the dock in it and as I resize the window the dot stage relative to fixed relative to the lower left corner that's because the drawing the coordinate system is relative to the lower left corner of the drawing environment you can see the white area here which represents the view and the view resizes and redraw automatically as I resize the window so one of the things you do get just by implementing that in a few lines of draw rect is you get a lot of other functionality available to you let me show you what I mean I can come two dots view and I can say makes up view of scroll view okay and let's make that scroll view also sizable now I'm going to save this go back to Xcode and let's build and run again so notice that suddenly our scrollview we our view is contained within a scrollview and we can scroll it and again just because you've implemented your view so it knows drawing you get scrolling for free let me show you one more thing you get for free let's undo this scroll view oops no not do that much yeah it gets your doctor let's get rid of the scroll view Wow hmm there and i want to show you how you can make it print now we haven't talked about target action will talk about in five minutes but one way to make it print is to connect the print menu item to our view and just select print here and i'll talk about this in a few mins if you haven't seen this before okay let's save it back in xcode let's build and run again okay so if i now were to go in here and say print we get a print panel and one thing you'll notice of course we don't have a printer if we're able to print you would get something like this this is the artist's concept drawing of what the dot might look like on paper but if you don't believe me I'll do preview which is always something you can do when you're testing your printing and the preview application will launch and you see that the dot is printed on that page okay okay so let's go back to slides please and next thing we want to do is it add some excitement to our demo and do some event handling as I mentioned earlier NSU is your class to do most of your event handling it you override methods such as mouse down mouse drag key down depending on what you want to do to handle the perfect kind of event there's also another class called NS event which represents various kind of events and you get event specific event specific information out of it for instance the mouse location the keyboard what key was pressed you know what tablets pressure and so on so with that stuff let's go back to our demo again and add this to our code so you can see it in action ok this for this will just need Xcode now one thing I want to do now is parameterize some things about our dot so we go back to the interface file you H now I'm going to go ahead and add two instance variables instance variables are declared in the header file in this area here so i'm going to add an instance variable that represents the center location of the dot in this point is a structure that represents a point i'm going to have a radius for the dot it's a floating point number note that coordinates are floating point numbers so we use floating point numbers where appropriate ok so we now we added two instance variables to r dot i'm going to save this file i'm going to switch to dock um back in the init with frame method the place where i said we do our initialization i'm not going to initialize those two instance variables so i'm going to delete this code i'm going to set the center 200 both the x and y locations of my center i'm an effective radius 250 so this is we're initializing these variables their initial values now here we were redrawing our dots using fixed numbers so let's replace this line to use the new instance variables so we now may correct with the ex- radius y minus radius 2 times radius etc so now we have parameterize r dot wrecked and finally let's do some event handling as i said you override methods like mouse down so we'll add a method called mounts down and we'll ask the event argument which is represents the current event for the location and window this represents the event location relative to the window the view is in so the next thing I want to do is convert that to the views on coordinates using this method convert point from view this gives us our sensor this is where we clicked this is what we want our center of our dot to be and note here that we're just assigning to our sensor variable you know pretty straightforward the one more thing we want to do now is given that now we have a new sensor location we want to redraw our view but instead of calling draw rec for instance to draw our view we just basically tell the view that it needs to be reedus played and then app kit will redraw your view at an opportune time later what this allows doing is coalescing various drawing needs to the top of the event loop so you're not drawing things over and over things and overlapping and so on so to do that you tell the view that needs to be displayed self sydney's display yes ok so it we take the event we assign our Center and we just tell it needs display so let's save and let's run ok now as I click around the dot is we displayed at the new location note that when I do this because I told the whole view to redisplay the whole bounds of the view is we displayed in the performance Tik Tok on Friday you can learn about how you can do this much more efficiently of course here we're just taking the easy way out let me show you one more thing I talked about mouse dragged as well mouthed rags and events you get when the mouse is clicked and it's being dragged will have Mouse drag do the same thing as a mouse down so we'll just call self mouse down let me save let me go ahead and run the app again now as I click around the dock moves but if I click and drag again the same thing happens so the view is being constantly reedus played being told to sydney's display and so on so that's just fairly straightforward to go ahead and make our dots dance and any way you want ok let's go back to slides please okay again drawing event handling those are pretty mundane things how about some UI elements so your app looks like a cocoa app or a Mac os10 app UI elements are represented by a class called NS control which is a subclass of NS view the daily controls you see the regular controls you see include text field buttons slider we also have some new controls a little more sophisticated token field date picker these are new and tiger we also have some really sophisticated controls table view browser browser represents the multi-column you you see and find their table represents a table of elements these are typically made up of other UI elements and they're fairly sophisticated but they're still subclass of NS control there's also this other class which we won't talk about today but let me talk about it it's the every control has a cell in some cases controls have multiple cells cells are basically what controls are made up of typically users user control however if you are subclassing control for your own purposes you might find that you need to also subclass the corresponding cell and that's why we're mentioning it here and in some cases like table views and browsers you might be using multiple cells to get what you want to get done to represent multiple pieces of that cells are not subclasses of views they are lighter weights objects the main design pattern for UI elements in cocoa is this target action design pattern target action with target action controls have a target and they have an action target is the object they send a message to when they're fiddled with so you play with the slider and says I've been fiddled with the action is the message they send so what they actually say they don't actually say I've been sidled with an action is a single argument method always and we'll see that in our demo and note that these are not magical things they're really just instance variables of controls okay so armed with that knowledge let's go to our next demo grab some water okay the thing we want to do now is going to be able to change the size of the dot okay now to do that we're going to be adding a method called change size which is an action method so this is an action method to change size colon and it has one argument sender and this is this is what makes an action method and the argument sender is the UI element that sense this message now we're assuming that the sender is something that's capable of producing a floating point number because we want to change the size of the dot so what we're going to do is ask the sender for its float value most controls have a method called float value that represents the floating point value that they've been set to we're going to ask for its float value nor even assign it to our radius instance variable which we had added last time and again just like we did up here we just need to sell Sydney's display so we're going to change the radius self Sydney's display now I want to do one more thing we've been adding methods to our m-file but we have not been adding them to our H file to our interface file for methods that you expect to be called from the outside world it's a good idea to do that so let's go ahead and add the change sides declaration to our da th file as you can see straight forward is it just change size colon with the semicolon representing that this has this method now we'll see why this is useful I'm going to switch back to interface builder now interface builder I'm going to tell interface builder to re-read gaddafi H file so if I go back into classes tab here i can say either by right clicking here or by going to the classes menu read files or read da th so this will cause interface ball to reparse doc you got H which means it now knows that okay let's see No it should know okay let me go back and see one thing pilot I'm sorry this was this is all this is all proper I'm wondering what I could have let me get it to read the file again just just in case let me say parse here go back to interface builder hide other stuff huh we're going to change size it's fairly straightforward stuff it shouldn't be okay i will change this to IV action which is often not necessary what I be action is another defined for void and what it says is it marks this method explicitly as an action for ID to recognize let's see if this actually does the trick it often is not needed so if i go ahead and reparse the file and let's make sure the file is coming from the right place it is not CH parts okay and sort of perplexed by this luckily at this point i will quit interface builder i will go to the oven and pull out okay so there we go pull out a finished version of that and that has always worked so I'm sort of curious as to what's going on there but if we look at da CH in the prepared version it looks exactly the same and let's go ahead and click on my main menu name to open up our main in file notice that if you look at doc you here oh I know what's wrong I'm sorry I I was just getting confused there it's not even in fact I will go back to our go back to our original one and we'll open that up go go show that there's nothing magical going on here let's open up our main menu nib okay so if i look at the class now that's you you'll see that it's got two actions to outlets should know about it the time you see your slides do your action is if you have a slider for instance and you make a target action connection you make target action connections by actually control clicking on the UI element that's going to send the target action and dragging towards the element that you want to the target to be so in this case dots you now I'm still not seeing that there I'd to know what that's about let's just go back to our pre-prepared version that's quite odd I don't understand it but okay so we're back in interface builder will open our main menu nib so if I make a connection from here to here you'll notice that the actions which represent includes print fax which were already there and now a change sides method and I just make that connection by choosing change sides and hitting connect and this establishes a target action connection between my slider and the view okay so sorry about that I know what was going on over there but let's now let's save this let's hide and let's go ahead and run our demo okay as you can see we can still move the dot around we can resize the window and as I move this the dots will actually resize that's because as I move this it's sending change size call and over and over and the change side method is changing the radius if you can remember back that far and then it's redrawing the view so that's that's what's going on the other things we did here by the way when we did the slider was in the attributes of the slider which changed so that you know we could change its minimum and maximum values the current value and we also specified that it continuously sends action while editing which makes it sends its action over and over again okay so that was that was our slider so let's go back to slides to talk a little more about target action so what we saw there was that the sliders target is the dock to you slider has two instance variables target and action in our document method called change size the target is set in its face builder to point to the dots view and the action is specified in interface builder to be selected of change sides colon but so this is where you see that select their business come in but note that you know we didn't have to do this programmatically or anything we're able to specify this in interface builder or we were almost able to specify the interface builder and interface builder store this information in that nib file as i said earlier target interaction aren't anything magical they're just they're just instance variables and you can set them programmatically using methods set targets and set action if you want okay now I'm going to talk a little bit more about target action but before that I want to talk some about memory management Coco objects are reference counted and probably most of you are familiar with this but I'll just make sure I go over what this means a freshly created object whether you create it with a lock and in it a lock-in it is the paradigm for creating new objects you allocate it being initialize it or whether you're created by doing a copy of another object if freshly created object is a reference count of one you call retain to add a reference count you call release to remove a reference count so this is just reference counting you have nothing really secret here and the object is deallocated when its reference reference count reaches zero and that happens by the object being sent a dialog method which is the opposite of a lock so let me give you an analogy here just to make sure this is a queer you go into a restaurant and you tell the waiter you want a table so the waiter goes and gets a table that's allocating the table then the waiter puts the welts a fancy place so he puts a table cloth on the table and even gives you forks and knives in place that's initialize on the table and you sit at the table so as long as you're sitting at the table the waiter is not going to come take the table away the moment you get up and leave you released the table and the waiter will come in deallocate the table and make it ready for the next person so that's getting rid of it now while you're sitting there if a friend of yours comes by and sits down at the table they also retain the table now there are two references on the table the waiter is not going to remove the table until both of you leave you know if eight friends come now there you know aids references to the table so until the last person leaves the table is the table is retained and copy let's make an analogy for copy you come into the restaurant and you see a table that looks gorgeous it's got you know a bunch of people sitting at it a good-looking table you tell the waiter I want a table just like that but you'll want to go sit at that table because you don't know those people so instead the waiter creates a table just like that for you that's like making a copy of that table but it's your own copy you don't care what happens at that table you got your own copy of the table now one more thing I'm going to mention at this point is order release I'm going to mention at this point I'm not going to talk about it for the rest of the talk what's an important concept it's like released but instead of releasing the object now it releases the object later and this turns out to be pretty handy given cocos object ownership rules and you will see this and probably use this in your programming of cocoa now having coverage memory management let's talk about object ownership in cocoa object ownership is important in dynamic environments where object oriented environments where you know you're constantly passing objects between things people are allocating objects and returning them to you and the question that's always asked is who frees this object in cocoa the answer is there's a consistent answer for ninety-nine point nine percent of the cases and that's object ownership is not transferred across calls what this means is if somebody returns an object to you as a result of a function call or a method invocation you do not free that you do not release that's it you just use it you know assuming you need to use it and that's that same goes for when an object is passive an argument the person who got the object does not free it they will use it now if it turns out that object is needed long term you can retain it and then release it later on so the rule is whoever creates an object or retains an object or copies an object you know whoever is responsible incrementing the rest count is also response for releasing it so basically this summarizes that you pass someone an object you don't care what they do with it they will retain it and release it if they want so with that let's look at little a little bit more of target action and do something slightly more substituted and this time we'll all pray to the demo gods okay so for this demo I want to change the color of the dot so for that let's go back to our dot view and let's add a new instance variable okay okay so we add a new instance variable color as i said earlier before colors are represented by NS colors and their objects they're not in store floats or anything so we have in color instance variable now let's go add a second method change color and hope this time we were able to parse this in so this is the method the action method that's going to be used for changing the color so I'm going to save eh right now let's go back to our source file doc um and let's add our change color method make this window a little smaller so you can see the bottom so the change color method we're going to ask sender for its color we're assuming that the sender is something capable of generating your color and we're going to call a method called set color on ourselves I could have done like here and just set the color in here but i want to show you just you know let's write an accessor at set method to see how it's written so we're just going to get this color from the sender i'm going to send it to set color note that here already you're seeing cocos object ownership rules in action we're getting a color from this thing but we don't free the color we just use it we don't worry about what happens to that color you know if we wanted it we will keep hang on to it and here we're sending the color to this method and again we don't worry about what happens in that that method will do the right thing so let's go right that method and you'll see what I mean setcolor takes a color as an argument and if the new color is not exactly the same as the old color that's both for optimization and for few other reasons but basically it's a good idea to do this if the colors aren't the same we release the previous color instance variable and we make the color instance variable point to the new color but we retain it because we want to hang on to it okay and the third thing we want to do here just like we've done in other places like here is stay fit needs display yes which of course because we change state we want to view to be redrawn so note this is basically what you know your typical set method might look like you release the old value retain the new value after checking they're not the same okay so now we know how to change the color let's do a few more things one thing I want to do is make sure our color is initialized so we initialize our color to the blue color and we retain it we hang on to it because we're hanging on to it long term in the drawer exmouth oh one thing we have to do now one thing we need to add is because we're hanging onto our color instance variable when we're being deallocated meaning when the view is going away we want to get rid of our color instance variable so for that we implement the dialog method i mentioned earlier and we'll release the color so the one we're going away we make sure all the resources we hang onto are going away and we call super dialogue super is the way you call your super class implementation and that's it so typically you will have dialogue methods which do you know which clean up your stuff and then you call super for it to take care of it we do one more thing instead of the blue color here we now just set the color we have so we just say color set if I'm going to save this right now and let's go back to interface builder interface builder I'm going to pull the slider aside i'm going to drag this little control this is a color well at lets you change colors now let's go ahead to classes and keeping our fingers crossed let's read files now we're in i believe we're in this directory right now let's just read that file and now we can make a connection from our color well here to the dots view and we choose change color connect so this is what should have happened before but anyway demo gods were taking a lunch break okay so now we connected that let's save let's hide or bring up interface builder and let's build and go okay so as you can see we can still change the size and if I click on here the color panel comes up and I can now change the color and you can use any mode of this thing you can use the crayon in any mode in the color panel you can as I said earlier you can use gray scale you can use CMYK and so on so all these colors are represent by nice color and they work in the context of our application okay so now having done all that let's go back to Xcode let's look at our dock view one thing you might be noticing at this point with dots view is it's getting a bit unwieldy it's got like 25 lines of code that's getting a little too big so let's see how we can start cleaning things up and making this a better structured app and for that I'll can we go back to slides I'm sorry we're going to talk about model-view-controller Model View controller is a is not not a Coco specific design pattern you've probably heard about it used in other cases but it is used in cocoa to create bigger better structured applications and it makes you know document based apps and so on much more easy to do and much more of a joy so Model View controller is a design pattern where you break your application to three pieces the model which is the back end of the application where your data is the view which is your user interface and the controller which is the middleman controller users usually has a variety of roles it usually manages the connection between the model in the UI and kind of other roles in some cases controllers can actually be fairly thin or you can cut out the middleman altogether in the very simplest cases turns out that's one of these cases here so we'll look at dot view and we'll see how we can separate the model in the view pieces here's what our doctor looks like now before our surgical separation of the back-end and front-end the doctor has a sensor a color and a radius these are the instance variables in the in our class after we're done with our surgery we're going to have a class called dots which has those three instance variables so the dots class is going to represent our dot and we're going to adopt new class and all the docu class is going to do is point at the dots so it's just going to have an instance variable that represents the dot so this is fairly basic MVC model view controller at this point the dot is going to point the dot instance variable is going to point at our dot object okay so let's go to the demo machine for this piece now okay so at this point we're going to add a new class so as we did before we come here and we say new file and this time I'm going to choose objective c class because i just want a subclass of nsobject dot is just a simple data bearing object now the subclass of you know subclass of control okay and let's call it dot dot m also create H okay so interface builder traits to files dot HTM in dot dot H we're going to go ahead and put our instance variables points radius and color so the same is some variables we have today okay now and let's go to declare some methods for dot we're going to have a set Center method to set the center and now you're thinking okay we need set radius and color for now I'm not going to do that we'll talk about that why and we're going to add a draw method and some of you are thinking draw dots is a model object why does it have a draw method well it's okay for model objects to know how to draw in this case it just knows how to draw but doesn't make any assumptions about where it's going to draw what you hierarchies and what the UI element is it just knows it's you know location its size and its color so when told to draw it can draw itself so it's an appropriate thing to do here so we'll just go ahead and add a draw method so let me now save this and switch to the dot implementation file dot am now an implementation file of dot we're going to add init method as I mentioned earlier in it is the way you initialize yourself in the context of the view class we saw in it with frame which was how created in the case of a simple enough object subclass like that we would use in it so we doing it we do super in it and if that succeeds we go ahead and neutralize ourselves set the center set the radius you've seen this before and set the color and then we return self so this is what a typical initializer might look like you know just like dot views now let's go ahead and give ourselves a dialogue method which is again just like da see you release the color in return now we declare two methods earlier let's go ad those the draw method this is again taken from dot view that's you we create our dot rekt we set the color and we draw the oval ok and finally we said we're going to add a set Center method let's go ahead and do that set Center is going to set the center instance variable to the point that's passed in here ok and for now this is all we're going to do we're just going to change the center note then the context of dots view we were doing self fifties display yes but here we're not doing that because this is just a model object and doesn't many assumptions about views ok so this takes care of our dot class let's save this now let's switch to our da coh in da th we want to remove our instance variables want to remove these two methods now that's nice getting rid of code is always nice less maintenance whatever your boss doesn't have to know you're doing less work but so now and then we can switch the doc um ok and use the similar modifications here to lighten the load a bit turns out we can get rid of image with frame ok because if we don't need to initialize any of this stuff anymore turns out we can get rid of sialic ok indirect which is how the doc you draws itself we will leave clearing off the background because the view still needs to draw itself but instead of all this code to draw the dot we can now tell the whoops I'm sorry that was a piece i forgot to show you in dot view I'm eh because doc you now references the doc object we need to import the dot dot H header file in addition we want to declare an instance variable dot which two pieces I forgot so the dot instance variable note that we have a iboutlet specifier here this just specifies that this is an outlet and we'll see what that means in a few minutes and an outlet is basically an instance variable that is visible to interface builder and you'll feed in a few seconds so let me save this again switch back to DA to you so back to draw rex back to the discussion there instead of drawing the dot we just draw the dot by telling the dot to draw so all that code is simplified now let's leave our mouse down and mouse drag in here because these are skill primarily view operations and we can get rid of change sides and set color and all this because we're not in the business of changing size anymore the view doesn't care anymore it's the dots responsible to be doing those things so get rid of this code so suddenly dot view has come back to a manageable size that's good so let's save this file ok now we now we need to switch the interface builder ok now one thing I wanna do is tell interface builder about our dot objects let's go ahead and say read files dot dot H the moment we say that interface builder Niles knows that there's a subclass of nsobject called dot now why do we do this why did we bring that into the picture because I want to go ahead and create an instance of that creating an instance of dot is just like what you did what you did here when you dragged ask you out of here if you basically instantiate the dots view here I want to instantiate a dot but dot does not have a visual representation our window because the model objects so you instantiate with this menu item here instantiate dot that adds it to are instances tab as a new object if you can see that here dot ok well that's good so now we have a dot object that represents the dot now when I go ahead to dot view i'm going to reread the dot view file let's go ahead and read the dot view file ok it's warning me that because we change the interface of the file the it's not compelled with the earlier let's say your place so now the doctor has been changed it now you know knows the new doc you not the old dot to you as a result of this change we can now connect that's you to our dot what's this connection about that's where we're connecting the dots instance variable of the dot view to our data object you can see here that the dot object is here it's known to ID now because we read the file I will go ahead and say connect so now this dots use dot instance variable points to this dot object go back there ok and the slider and this color well we'll leave here for forms for now ok so I'm going to save I'm going to hide or we have xcode I'm going to run this oops failed with this one little mistake oh yes I forgot to finish some of the coding here sorry about that if we look back at the by the way this is that was a case of a build failure when you click on this little one here it tells you that Center is undeclared and indeed in the in my methods here in mouse down we still refer to Center I needed to change the mouse down method instead of doing this I knew just need to tell the dots to set the center because remember we gave set Center method to dock so we tell dots to set center and we don't need to do this anymore and for now I will need leave the cells needs display in place ok so with that hopefully we're bug-free let's run our application let's hide it ok so there's our dot it still moves around ok and we didn't connect the slider the color well so we can't do much so you're thinking ok we did NBC now our app is even less capable and so I'm going to be bringing any more revenue what why did we do this well the magical end we see is that the UI and the model are separate and that means that you can tweak the UI in ways which the model doesn't care about an example of what that means is i can now come here drag a new window out I can come to my containers tab dragging your custom view out let's just put it all the way there okay let's make our custom view let's make the custom view an instance of dot view just like the other one let's make it sizable just like the other one and let's connect the dots of this dot view to the same dot okay okay there you go so now we have two windows in our application one more thing when they do in our window is visible at launch time so the window is visible when the app is launched because my default secondary windows won't come up until you ask them to be brought forward in this case we want it to be visible so we do that let's go back into Xcode let's run our application okay so now we have two two windows with da znam and I claim the dots are the same well if I click here you might at you will think you hey that's not they're not the same well they are if I resize this window this one jumps to the new location so they are the same it's just we got some connection problem here where we got some synchronization problem but as you can see already the promise of MVC is begin to shine through I have the same dog visible in two different windows and we're able to add a second view to our dot with you know no code it was just not integrates builder so what do we need to do to get these dots to synchronize each other and so this now is when we start talking about a few other things that make you know expand the picture of NBC in in cocoa so if we can go back to slides so now we're going to talk about kvc now we have MVC we have KBC don't confuse these with mfc or KFC you know one's a fried chicken and one something else k vc is key valley coding it's a mechanism to set or get and object if the properties on objects indirectly well i mean by that is you use these methods set value for key and value for key and the property is the property you want to set or get okay we will use rules shoulders neck now so in with kvc instead of calling set color on my dot I would call this method set value colon for key pass the string color that's the property and I would pass the new value now you're thinking if I have to go right asset value for key method so that KBC works the answer is no KBC uses on objects existing access your methods or its instance variables to do its job so if you have an instance variable named color or if you have access through methods name setcolor colon in color which is the way you would set and get the color note that you can also have set color colon and get color if you like the name your things get we in Cocoa we often don't do that but you know that's another with naming style assuming you have these one of these two ways and a bunch of other possibilities your dock view your dot object becomes kb c compliant for the property of color ok and you don't have to write any code i mean automatic if you have a variable called color you are KBC compliance for the color property yes that's fairly simple now let's talk about key value observing just quickly because this is needed to complete the picture p value observing kvo enables observing changes in kv c compliant properties what i mean by that is you know if you have a kb supplying compliant property color you can observe changes to color here's the method to use this is the gnarliest method I'm going to show today luckily we won't be using two of its arguments so just ignore them you can add you can observe some objects property by adding yourself so this argument your observer for the property and you send it to the object you will observe that's what this does and whenever that property changes the observer will get this method observe value for key pass the property in question and of object now a whole lot of methods here it's probably best to show this in action and that's what we'll do right now little kvo to see our dots work better okay so turns out this is just in Xcode now because our IV connections are all done and they should you know they're pretty close okay in Xcode so all the changes now our needs and doc view because our dot object is already KGC compliance for those three parameters because we've added them as instance variables they're there so in Doc's view we just want to do a little bit of observe observing to do that we will add awake from nib methods awake from nib is a method that gets called when objects are loaded from a nib and all the objects are been finished loading awake from knit is called and all the objects to get them to do any additional initialization they might need to do so this is not like the init method which is fairly early this is a this is called after everything's been created so the world is a little more consistent so in a way from nib we establish our observations and the way we do that is we tell the dot object to add observer self so the view is becoming an observer of dot for keepass radius because we want to observe the changing of the radius and the arguments you're supposed to ignore now we do that two more times not like that click here and do it again for center and four colors so we're observing the properties of the dot we care about okay so pretty straightforward just three observations now the next step as you may remember is now you need to implement the method which gets called when the observation is done when that when the sink changes and that's this method observed value for key path of object change context and in this method we're now this message will get calls whenever the radius to center or the color changes but I don't really care which one changes all I want to do is read through draw the view so all we're going to do is say self set needs display yet that's all we're going to do whenever we hear that there is a change now of course in other cases you might want to do more specialized things now for completeness i will show you one more thing you should do and that's to remove yourself as an observer if the appropriate time this could be depending on the application will be different in this case we do it in the dialog method so as the view is being deallocated it should remove itself as an observer for the three variables that added itself force and that's these three lines remove observer for keypads no reserve for keypad no survey Cuba pretty straightforward now let's come down here the draw rect doesn't change there's one more change we can do right now note that before we were cheating in mouse down in addition to setting the center we were causing the view to be we displayed and that explained why the view itself updated when I clicked in it but the other view didn't because the other view did not know to display itself but now that we have this great observer mechanism I can move this line of code here because here we just tell the dot here's your new location and the dots will hopefully tell us that this location changed and will we display everything okay so let me save let me go back to interface builder I'm sorry not interface builder let me build and run or quit the application build and run okay so now if we did it right demo gods were are with us as I click here and move the other dot also moves and you know it's there perfectly in sync and they're both doing self Sydney's display they don't know about each other and the good thing is our dot object the model object knows nothing about these views absolutely nothing it's just told to draw in each view by the view when the time comes so there you go now one last thing wanna do is these duds here the slider and the color wheel aren't connected and let's hook those up okay so back to the slides please and that brings us to bindings now bindings was introduced it's a technology into houston panther its its technology that is used to automatically keep attributes of different objects in sync or to be a little more exact it keeps model and view values synchronized and it eliminates the glue code you often need to create for that purpose by glue code I mean the kind of code where you know you respond to the slider changing it might be an action method and as a result of slider changing you want to update your dot size and maybe you want to go update a text field maybe going to go change something in a database and so on you know you're writing glue code all the time in many cases even in cocoa if you're using target action such you find yourself writing blue coat over and over and this is what bindings eliminates and we'll see of course how that is with another demo bindings leverages KBC and kV 0 and it's very well with MVC so and again we'll see how bindings can be added to this application easily so exactly what bindings lets you do is it lets you bind attributes of views the properties of model objects that's worth repeating look there you go and it's worth showing a picture for so here's our dot so the dot has the properties it's a model object that's properties sense your color and radius here's our slider now I've removed the target action message from slider in this picture because now we're not dealing with target action anymore instead we're just looking at the value of the slider is an attribute of the slider with bindings i bind the floating point value of the slider to the floating point radius of the property of our model similarly I have a color well and I bind the color value of that to the color value of my dot so with bindings this is the kind of connection you establish the good thing here is that what this implies is if I change the dots color the color world will change if I change the color wells color the dots color will change so it it's a two-way binding and bindings of course uses a que vou know the observing technology we saw earlier under the scenes to get this to happen if you were to call a binding method to establish the binding programmatically you would use this method bind colon to object blah blah here's how it would look like I will tell the slider to bind its value to object dot to its property radius ok this is how you would do it luckily you almost never call this method it programmatically because bindings are usually established in space builder as we'll see right now okay if we can switch to the demo machine the good thing is you know I'm talking about bindings and interface builder at this part of the demo doesn't involve Xcode anymore it's just interface builder so let's switch to integrate builder okay so here's our window one here's our slider now for this part for establishing binding you go to the bindings pain of our inspector here okay and you'll see that slider has its max value its min value and its value ready to be bound so these are the attributes of a slider you can bind it's also got enabled hidden and so on and you're also has tooltip so you can bind any one of these in this case your interest in binding the value so I'm going to click here now you can bind to any object that interface builder knows about in your nib file well knows about the dot because it's right there in our document so I'm going to bind the sliders value to the dot object I'm going to bind it to the key past radius ok that's the property by keep a tiny property there so I'm not established the binding between the value and the dots radius game let's do the same thing with the color well I'm going to bind it to the dot I'm going to bind it to the keepass color ok so let's go ahead and save and let's go back to Xcode and run and let's move this so there you go just with two connections in interface builder we're able to bind that slider to automatically track the dot and you know the two dots also of course also track each other and saying with color i can bring up the color panel and i can change the color and again this is now bound to this to the dots color value and so on and of course bindings you know this is not the only thing bindings gives you let me show you the little other magic of bindings I can make my slider smaller I can go to the text here I can drag out the text field as you can see and again I can go to the value binding of the text view here so if i go to hear the attributes go back bindings here's the value binding I'm going to look in there and set the value of the text field to be the same as the radius save go back to Xcode run as I move the slider not only is the dots radius changing but now because this text field has been balancing the radius the text field is also showing you the exact same value as the slider does so as you can see without any glue code without writing any code to bind those things together you know and get to make sure they're in sync we are keeping things in sync the good thing here also is that the initial case situation here the dot the model values from the dot the fact that's blue and the high is 50 and so on are automatically also reflected on these in developments at launch time okay so just to we can go back to the slides just to show you a picture of what we did there with the text field we added a text field and we bound the value to the radius of the dot again you can establish multiple bindings to the same property and they will be kept in sync there's a there's a lot of magic in a lot of great stuff and bindings and especially when you start using controllers which app it has sports for you can use tables outlined use browsers and so on in your applications with writing it hardly any code or no code at all and and you can go to the binding stock which i think is tomorrow to see more about bindings okay so what we saw today is an overview of cocoa objective-c xcode ID in some fundamental cocoa topics drawing event handling target action object ownership KBC kvo and DC and of course bindings and we also saw hopefully that simple things were simple meaning very little code is needed and even complex things are possible where we have to resort the may be using is using observers for our custom views so hopefully you know that idea got true you can go to the tips and tricks talk cocoa tips and tricks talk tomorrow to see more of this simple things simple and complex things possible theme with George your demos and further advanced things now some things we don't see there's a lot of stuff in cocoa and as I said a few good solid design patterns and the few we don't see include delegation which involves objects helping each other that's a powerful design paradigm that we didn't see but you probably need to be aware of notifications which is where objects are telling other objects they did things categories where you can add stuff to objects at functionality to objects data sources were again objects are helping other objects and immutability where objects refuse to be changed these are some of the design patterns that you probably will become familiar with you run across in learning cocoa other things we don't see include some features of cocoa and here's a you know not certain a comprehensive list but doc you make sure undo localization etc a lot of great features there's also other frameworks which are not in the cocoa umbrella and are not core cocoa frameworks but provides objective-c api's that can be used easily from cocoa and one of those is of course the core data framework that you saw yesterday the resources for you to you know learn more there's the apple developer connection which has the cocoa page and in there there's getting started with cocoa which is fairly useful has links to many resources that you want to follow the O'Reilly books for cocoa there are some pretty good books for cocoa objective-c and there are other books including aaron hillegass is a programming cocoa book and a few other third-party books they're all pretty good aplin Omni both have developer mailing lists and of course the sessions here at double wdc there's a bunch of just core cocoa talks and many other talks related to cocoa an objective c api so i hope you get a chance to chance to see them and enjoy them and that's it for my part thank you very much [Applause] [Music]
