[ Silence ]
>> OK, welcome back to S-76, so tonight we actually dive
in to iOS programming, building on the material that you dove
into with Rob last week.
And what was that language
that we spent the latter half of last week on?
>> Objective-C.
>> Objective-C, exactly.
So, let's see if we can take a whirlwind tour of some
of those topics and see if this will lend itself
to recognizing some of the same constructs you saw last week
albeit in a different context namely GUI programming today.
So, here was a canonical program of main.m. Dot M,
that was probably a new file extension for some folks.
What's the dot M referring to?
>> Refer to methods?
>> So, methods typically.
So, methods are where you actually implement your
functions or your methods and this is
in contrast with the dot H files.
And the dot H file in Objective-C contained what kind
of things by contrast?
>> Interface.
>> So, the interface or the sort of the information
that describes what the code is that you're about to implement,
and this is an example that we'll see pretty much
in every iOS application that we make, certainly ones
that we make by starting, from some of Apple's templates
and it is-- I cannot think of a single instance
for the next four weeks
where you should ever actually touch this file.
So, you can take comfort in the fact
that the way you get it is the way it should remain
but it actually is the file that kick starts a lot of the magic
that then proceeds to happen,
and we'll start giving you a tour of that today.
So, let's work through this line by line as representative
of some of the syntax we'll continue
to see even though it won't be in this particular file.
So, slash-- hash import.
What does that do for us?
First line in a file like this?
Yeah?
>> Import the library.
>> Yeah, it imports the library.
Specifically the library that's called the foundation library
which for Objective-C is all the basic stuff that you get
with Objective-C things like arrays and other types
of objects, sort of like Java's collection classes and the like,
so-- or things you might get in C++ is standard library.
So, a lot of functionality right out of the box
and a hashtag import means
that those method declarations will be automatically loaded
into this file so you can just start using them even though
someone else implemented those functions and those classes.
So, int main just means
that this function returns an Interviewer.
For our purposes that will pretty much be inconsequential,
but this is one of the means
by which programs can signal whether they were successful
or not.
If a program like main returns 0 that means all is well.
If it returns anything other than 0,
what does that typically signify?
All is not well, and there can be almost an infinite number
of things that could go wrong and that's why we use 0 for good
and unknown 0 value for anything else.
Argc and argv typically refer to command line arguments,
things you would actually provide to a program
by typing commands at a keyboard.
That's not going to be applicable
for our iOS programming.
And then inside here we see some syntax that's new
to Objective-C, most everything else we have seen thus far is
exists in C or in a form similar to C
and autorelease pool refers to memory management.
And we'll come back to this over time but in recent version
of iOS, a whole bunch of useful functionality was introduced,
that essentially means that we can start thinking
about memory a lot less.
And I'll point out for here and there exactly
where there is interesting memory management going on
but know that two years ago had you taken this class your lives
would have been much more challenging when it comes
to implementing some of the stuff we'll dive into today.
But Apple has lowered the bar to getting
into Objective-C programming in part by hiding some
of the complexity of memory management.
NSLog is just a function like printf
that will print a formatted string but to a specific place,
a standard logging mechanism that we'll actually see in Xcode
which recalls the IDE we'll use to program in Objective-C.
Return 0 means that we're assuming all is going to go well
and we will pretty much never see this function again.
Yes, questions.
>> Should we start every program with autorelease?
>> Good question.
Should you start every program with autorelease pool?
Short answer yes but objective--
Xcode will actually write this code for you.
So, we'll actually see in a little bit a function quite
like this but with one additional line
that kicks off the magic that is the SDK that comes
with Xcode for iOS programming.
So, you can [inaudible] literally just take what's given
to you out of the box.
All right, so, here is some syntax, and just to be clear,
I've gone into Rob's slides and I've deleted some
of the comments so that we can put them back to make sure
that we're all in the same page before we forge ahead.
So, this is what you might see
in a dot H file or a header file.
You said a moment ago that this is where declarations of methods
and other-- and classes might go
but not the actual implementations.
I have two comment symbols here.
What goes where that first comment symbol is specifically?
What do you put inside of an interface declaration?
So, instance variables?
And what's the definition of an instance variable, to recap?
[ Pause ]
[ Inaudible Remark ]
OK, almost the circular definition here.
What's an instance?
Instance of what?
>> An instance of a class.
>> An instance of a class otherwise known as an object.
So, an instance is just an object, an instantiation
of a particular class.
An instance variable is a piece of data, maybe it's 8 bits,
maybe it's 32 bits, maybe it's even bigger,
that's specifically associated with the specific object
that was created using some class
as its blueprint, so to speak.
So, this is where our instance variables might go.
And how about outside of the curly braces
but before the @end symbol,
what goes where those second comment marks are?
>> [Inaudible] class methods?
>> Class methods, sure.
So we can declare class methods there, not implement them
but declare them, which means, hey compiler, here is the name
and the signature, all of the arguments for a method I'm going
to implement elsewhere, elsewhere being the dot M file.
And what else besides class methods can go
where that second comment symbol is?
Instance method.
So, instance methods or sort of the opposite of class methods
in the sense that a class method can be called even before you--
>> Instantiate.
>> Instantiate an object.
So, if you just know a classes' name,
you've never actually used it as the blueprint
for creating an object, you can call on class method
on that class without an object existing.
And this is hugely useful 'cause you saw one at least last week
that allows us to avoid what would otherwise be a chicken
in the egg problem.
If we didn't have class methods, we could never allocate
or alloc an object of a particular class,
and that was the plus alloc that you might recall from last week,
and we'll continue to see tonight.
An instance method by contrast is one that you call on in--
on an object or particular instance of a class.
Exactly. So, we'll start seeing a lot of this
and we'll start writing our own classes in this way.
But there's one last syntactic detail that's worth recapping
here, the colon space NSObject means what, with respect to Foo?
[ Inaudible Remark ]
It inherits from the NSObject class.
And most classes that we would ever write, most classes
that you'll use in the SDK that Apple provides due at some point
to send from NSObject even though there's typically even
more layers than just one between you and that root class.
So, we'll see more of that in the time to come.
So, instance variables and declarations of methods.
And these slides are online if you'd
like to download them as usual.
Dot M files contain implementations, and this is one
of the sort of unfortunate design decisions of Objective-C
that you may recall last week.
Even though you do have balanced curly braces in a lot of places,
you also have wonderfully asymmetric ways of starting
and ending a sentence, so to speak.
You have @implementation and then @end which is the opposite.
But we saw this a moment ago.
What goes where that comment symbol is?
[ Inaudible Remark ]
The definitions
or the implementations of those methods.
So, you typically begin by copying
and pasting the declaration or the signature of your methods
from the dot H file but then you proceed to open a curly brace,
implement it and then close a curly brace,
and we'll certainly do that tonight as well.
So, there go our definitions of methods.
All right, so now a bit more syntax.
Messages we looked at last week, and this is a valid line of code
that assumes that a class called student already exists
and has been declared and defined elsewhere.
It could someone in-- somewhat technical
but roughly layman's terms explain what the two halves
of this line of code are doing.
Let's start with the side on the left of the equal sign.
What's going on with those symbols?
Students star student.
Yeah.
[ Inaudible Remark ]
Creating an object with a pointer called student.
Close but we're not doing as much
as you just proposed that we're doing.
We're doing a little less.
Yeah?
[ Inaudible Remark ]
Again, I'm going to define fault
with your use of create an object.
Yeah?
[ Inaudible Speaker ]
Exactly. Perfect so, create a pointer which is just storage
for an address and the name of that pointer is apparently going
to be student in lower case and that pointer is going
to point to, in other words, store the address of an object
of type Student capital S. So, all that is happening
on the left hand side of that screen is
that we're allocating probably 64 bits or 8 bytes
to store the address of what will be a student object.
But at this point in the story, only looking
at the left hand side of that line of code,
none of the object instantiation has happened yet.
All we've done is created an empty place holder
for what will be the address of some student object.
So now we can rewind and go with the right hand side.
What's happening on the right hand side of the line of code?
[ Inaudible Remark ]
Exactly. On the right hand side of the code we are allocating,
in other words instantiating an object of type student.
And what that syntax with the square brackets is presumably
doing is somehow returning what
to the left hand side for assignment?
The address.
So alloc is apparently not only allocating the object,
it is allocating it and then handing back the address,
something like one, two, three, wherever it is in RAM,
and so that known value is what's gets--
or getting stored in the left hand side which is
that 64 bit chunk of memory designed
to hold the address of an object.
A hand, OK, Peter.
>> So, without calling init,
is it actually an instantiated object
or is it just the added memory has been allocated?
>> Good question, just the latter.
So when you call alloc, all you have done is allocated the
object and therefore returning its address.
You have not initialized it.
But in many cases, initializing it doesn't have an
actual effect.
It's rather a human convention, programmer's convention
that we've adopted in the world of Objective-C,
that even if your init method doesn't do anything,
it should exist by convention.
You should call it so this line of code
out of context is not complete.
We have not initialized the object just yet.
Now because student, and in the previous slide Foo,
descend from presumably NSObjects,
the folks at Apple essentially gave us
for free an implementation of init for any descendant class.
So we could call init here.
We could call init on a Foo object and rest assured
that it will actually work.
It just so happens that the person
who implemented the init method
for NSObject just essentially returned immediately.
They didn't actually do anything 'cause you won't know what the
descendant class is-- how it's supposed
to be configured anyway.
So in short, whenever allocating an object,
you should always allocate it with alloc
or some similar mechanism as we'll see, convenience methods
as they're called, and initialize it.
But you sometimes have different ways of initializing objects.
There are methods beyond just the one called I-N-I-T.
There're longer names that we'll sometimes see,
and we can create them ourselves.
Yes.
>> Autorelease pool will release that memory at some point?
>> Good question.
It's not so much that the autorelease pool will release
that memory at some point, but we have created in main a pool
of memory designed to be autoreleased
by the operating system later.
So short answer, yes, but not quite with hat language.
This object will eventually be freed
when the operating system realizes no one needs this
object anymore.
And that's the difference vis-a-vis two years ago, we,
the programmers would have had to keep track
of when we're done using this student object
and explicitly free it or deallocate it later.
But we no longer have to do that.
All right, just a couple other things to recap.
So there's that student init method.
And I keep calling these methods,
but really in Objective-C the lexicon is a little different.
When you have open bracket student init close bracket,
you're not exactly calling the init method,
you're passing the init message to the student objects.
Now at the end of the day, it's functionally the same thing.
It's just sort of a different view of the world.
But when you see messages being described,
the message is the act of calling a method if you come
from the world of Java or C++ or other languages
that have more conventional methods.
How about these bottom two?
Student age and student set age.
What do you think the first one, student age, does?
It's a valid expression.
Yeah.
>> A getter.
>> It's a getter.
So that presumably returns the value
of an instance variable called age.
All right, how about the one below it?
So a setter, so in this case it's presumably setting some
instance variable to the value 20.
All right, and it turns out as you may recall,
the instance variables underneath the hood might not
even be called that exactly.
That's implementation detail for which there are conventions.
But we'll see over time how we can choose those instance
variables on our own.
All right, a couple more complex topics, not that you have
to be totally comfortable with just yet but just be mindful
of as we see them later tonight.
So a category allows us to do what, if you recall?
Yeah.
>> You can-- it's like an extension to the class.
>> It's like an extension to a class.
What do you mean by that?
>> So you-- if you had NSString for example and you wanted
to add more methods to that or [inaudible] do
that with your category.
>> Yeah, exactly, a category allows you
to add more methods to an existing class.
This was-- is particularly helpful for large classes
that might have let's say a hundred different methods
or a hundred different selectors that you can pass to objects,
and you just want to kind of categorize them.
You want to have the messages related to this functionality,
different messages related to this functionality.
You can put them in distinct categories.
You can put them in distinct files.
Different people can work on different subsets
or functionality for a class.
So they're useful in that regard, somewhat similar
in spirit to JavaScript and the prototype property whereby you
can add functionality to existing objects
by a somewhat similar mechanism.
All right, and we will also see them in the context sort
of a clever trick that folks have adopted.
We'll also see them as a means
of implementing effectively private members, private methods
or instance variables to a class that you don't want the rest
of the world to know about by putting them in your dot H file.
But we'll see that by example.
Yeah?
[ Inaudible Remark ]
Good question.
So by what guideline do we decide
where to put our method declarations,
for instance why might we put baz inside of a category
as opposed to somewhere else.
So, a couple of reasons, just to recap.
One might be if I am the guy implementing the bar category
of methods, I just have chosen for development convenience
to put them all in one file, therefore all in one category
so that I can kind of mesh nicely with colleagues
who are implementing other categories of methods.
So it's just programmatic convenience.
But we'll also see instances where if you want
to have instance methods associated with a class
but then you want them effectively to be private,
not broadcasted or advertised to the world, you don't want
to put them therefore in your dot H file
because then anyone poking around it,
your library would see them by nature
of what a header file is meant to be.
It's meant to be included by other people
or imported by other people.
So you can tuck them away and still document them
and still teach the compiler that they exist which is helpful
for you using Xcode since it knows more about your code,
but you're not advertising them to the rest of the world.
And it doesn't make them truly private
because you can still send any message to any object
that you want and just on a whim hoping that it exists.
And if it exists it will be responded to.
But it's a mechanism
to approximate that idea of privacy.
It's just not strictly enforced.
So I would think I'd keep those two guidelines in mind.
And lastly, protocols.
This is more complex manifestation of this
than we'll see later today
but a protocol let's us do what in Objective-C.
Yeah?
>> [Inaudible] set of methods that should be implemented
by the class that implements the protocol.
>> Exactly, it allows us to define a set of methods
that should be implemented by some class
that adheres to that protocol.
So if you're familiar with Java, it's effectively an interface.
And other languages have the same conventions.
It is a set of methods that you, a class, promised to implement
if you declare yourself as adhering to that protocol.
And there are ways of specifying that the methods are optional.
But by default, they would typically be required.
And the compiler will yell at you
if you say I am implementing the NSCopying protocol, but you,
the programmer, forget to actually get
around to implementing the required methods
to make that possible.
All right, so the biggest takeaways
from this recap I would say are one, what a pointer is.
Two, what an object is.
And I think those two would make--
make me pretty happy moving forward.
So just a recap, an object is an instantiation
or an instance of a class.
A pointer is?
>> That's an address.
>> It's an address of some piece of data and then
that will often be the address of some objects.
So if you're comfortable with those two definitions,
I think we can get through this.
All right, so iOS.
So, iOS adheres to a design paradigm generally known as MVC
which stands for, as you might guess, Model View Controller.
So we're not really going to spend any time on the M today.
But we will spend time on the C and the V,
the controller and the view.
And you can think of the controller of a program
that adheres to this MVC paradigm
as really being the brains of your program.
It's where you probably spend much
of your time implementing your program's logic,
responding to user interactions, displaying things on the screen.
But with that last goal, displaying things on the screen,
all you do is tell someone else to actually do the rendering
of information on the screen.
So if I'm a program for instance that's--
whose purpose in life is
to display someone's account balance in their bank account,
I being the controller, would respond
to the user's username and password.
I might somehow check that their username
and password are correct when they log
into the bank's website.
And then I, the controller, upon realizing, OK,
this is user David, I'm going to go check his bank account
and I'm going to check that by asking someone called the model,
but more on that in the future.
Once I have that value like 100 dollars, I'm then going to hand
that value 100.00 to something called a view
to actually present that information to the user.
So in other words, data is typically stored in the model.
In this case, that's where my financial numbers might
be stored.
The controller is going to be the brains.
All of the code that you write that sort of--
it respond to ifs and elses and for loops
and while loops will often be inside of your controller.
And then when it comes time to display the results of all
that number crunching to the user,
you typically hand the data that you have gathered
or computed off to something called the view.
And the view takes at that last mile.
It's sort of the HTML and the CSS of the world of the web
in the context of iOS.
It's going to have to do
with what the user sees on the glass screen.
So this is a paradigm that you should keep in mind
because that many junctures, particularly
with the iOS project, the staff's choice,
you'll have to decide for yourself
where do I put this variable.
Where do I store this data?
Where do I actually display something on the screen,
and the goal with adhering to a design paradigm like MVC is
to not blur these lines and to adhere to these best practices
so that when you start collaborating with someone else
or when some new device comes out like the newest iPad
which is maybe bigger than the two existing iPads,
you don't have to change how you're representing your data.
You don't have to change any of your so-called business logic,
the guts of your program.
All you have to do is change or add a new view.
And this makes it super easy to deal with things like iPhones
and Windows Phones and Android devices.
And all of the different displays or views
that a user might interact with, you don't have
to touch the essence of your program.
And that just makes life much,
much easier as your programs get more complex
and more interesting.
All right, so here is now, oops, how an iPhone application
or an iPad application works in more detail
than we need for today.
But let me go ahead and zoom in on a portion of this.
The key feature of this picture is the fact that there is
that circle in the bottom left hand corner generally known
as an event loop.
And as you might imagine, if you have an iPhone
or an Android device or anything that's a touchscreen these days,
for the most part it's just sitting there for the entirety
of its life waiting for you to do something or waiting
for something external to happen like an SMS message coming in
or a phone call coming in.
So it makes sense that the essence of a smartphone
or a tablet these days is just to sit
in an infinite loop waiting for something to happen.
And that's indeed what's really happening
in some form underneath the hood.
So this is a picture from Apple's documentation.
The URL for which is at the bottom of the slide if you'd
like to read the whole article.
And when you launch an application, you tap an icon.
The main function gets invoked which just like in the world
of C and Objective-C independent
of iOS is the first function that gets called.
We'll see that there's typically a function called
UIApplicationMain that's called by default, by convention just
because Apple designed the infrastructure to run that way.
And then we load the main UI file.
UI being just user interface, so something having to do
with the visual aspects of my program.
First initialization, whatever that means.
Maybe it's loading some of my top scores if it's a game
or maybe it's loading my bank account information from cash,
something like that, some piece of data.
And now we have a fork in the road.
Well let's see-- let's just go straight down and assume
that I haven't written any code yet.
We're going to restore the UI state.
So if I for instance played this game five minutes ago
but then had to take a call, maybe I need to redisplay
to the user where they paused the game rather
than starting from scratch.
So that's what we mean by restore UI state.
Final initialization, whatever that means
for my particular program.
And then once we reached this blue rectangle,
we've activated the app and just start listening for the user
to touch the screen, for a monster to come
by on the screen, for a phone call
to come in, for an SMS to arrive.
We just keep waiting for something interesting to happen.
Meanwhile, stuff can happen.
And this line going from left to right to left
to right is we're pointing at this box that says handle events
where an event is any of the things I just described,
something external triggered by the user or external triggered
by the network to which you're connected.
Now meanwhile, we have some slightly more technical detail
on the right.
This is the last portion of this picture.
On the right, everything in this big white box is my code
that I've written.
So we've seen a monospaced font some functions or methods
that we'll soon see in some actual code.
And for instance, one of the functions
up there is called application willFinishLaunchingWithOptions.
This is a common characteristic of Objective-C methods.
They are atrociously long named but they're very descriptive
and they capture-- their names describe what their arguments
or parameters are, various methods
which is a nice hand wave there.
Application didFinishLaunchingWithOptions.
So notice the difference.
First one will finish so it's about to finish launching.
Did finish means it's after the fact.
So if your code needs to do something before or after
that change in state, you have that control.
And then lastly down here, applicationDidBecomeActive.
So if you have-- [inaudible] implemented a game,
this kind of implies that you can
for instance immediately resume the game because somehow
or other Apple is providing you with these hooks
into interesting key events.
And this is quite like we saw in JavaScript with the world
of DOM, onclick, onsubmit.
All of the interesting things that can happen
in JavaScript can happen
in similar spirit in the world of iOS.
So this white box is what we're going to start writing today.
And Apple has written all of this stuff for us
and essentially just allows us to hook
into this event loop waiting and listening for interesting things
to happen just like JavaScript and jQuery allow us
to do quite readily in the world of HTML.
Yeah?
[ Inaudible Remark ]
Good question.
Short answer is it depends on who,
what kind of action is and where it happens.
For instance, if you have a program that's running
and you get a phone call,
Apple's threads can take higher priority
and therefore interrupt your program and actually show you
on the screen who is actually calling.
So multithreaded, yes, but not necessarily in the sense
that you can't continue running while
that phone call is in progress.
So there's certain design paradigms that Apple adheres
to that forces your threads to go to sleep
when more important things happen.
And this is in contrast to the world of say Android
which lets you do a lot more.
And the argument longstanding for Apple has been
that this way they can police battery life better
so that you don't have some thread
in the background just churning and churning away.
But the price we pay is that if you run
for instance the Gmail app on your phone,
you can get notifications and be informed that you have new mail
with the little badge number being incremented.
But if you want to actually check your mail,
you have to load Gmail, refresh the screen, wait a few seconds
and then see your email.
And I bring this up as an example 'cause it drives
me nuts.
Whereas the built-in mail application has more-- a more--
is more tightly coupled with the operating system
and can actually do all of that
in the background in its own thread.
All right, so UIKit is where we begin our look today.
And UIKit is just the user interface related SDK
that Apple provides to the world, software development kit.
So these are some class names
that will quickly become familiar to us.
Some more so than others and they describe different classes
that allow us to do different things.
UIApplication is the class that describes an iOS application.
UIApplicationDelegate is similar in spirit and we'll come back
to delegation and protocols later today.
UIView describes the aesthetics of a program.
It's a class that represents something that's on the screen,
maybe it's a rectangle, maybe it's a button,
maybe it's a text field.
So something like that.
UIViewController is unfortunately named--
Apple calls controllers view controllers.
So they are distinct.
View controller is the C. UIView is the V. View controller is
again just a C, not a V. It's the brains
of our application typically.
And UIWindow is just a class
that represents the rectangular piece of glass in some form
that your application is going to run inside.
So let's go ahead and write our first application.
It turns out we have different starting points
that Xcode provides us with.
We don't really have to use any template code
that Apple provides, but you'll typically find
that it's a great way to get started quickly even
if you just start with an empty application.
So let's do this.
Let's see if we start by loading X code here and going
up to the file menu and going to new project.
So not new file but new project.
So I get a whole bunch of folders
and a whole bunch of files for free.
Notice that we've got some organization here.
And last week you may recall poking around with OS X
because we just needed some simple Objective-C programs,
not necessarily iOS.
Tonight and hereafter we focus only on the top half
of that menu under iOS where we have an application category,
framework and library and other.
Most everything we'll be interested in.
For now we'll be under iOS application.
So here are those same template names we saw a moment ago.
And if you're familiar with an iOS device,
you probably recognize some of the design paradigms here.
The master detail view looks like it has a little menu
on the left hand side and then more information
on the right hand side like the built-in mail application.
OpenGL Game refers to a graphics-based game.
Page-based application means something that has
that sexy page curl that happens from the bottom up.
Single view application is a place we'll spend some time
today since it just allows us to have some basic sample code
and to get started quickly with a user interface of our own.
Utility application which is something like the weather
or the stock application super simple
but typically have a button that allows you to flip it
around to see some settings.
And indeed that's the template you'll use
for the next projects starting Wednesday onward.
And then the last one down there is tabbed application
which is also a common paradigm at least in iOS 6 and prior.
We have got some big icons at the bottom
that toggle state among different portions
of a program's functionality.
So, let's do something super simple like Empty Application.
And according to the instructions,
this template provides a starting point
for any application, it provides just an application delegate
and a window.
So, let's see what this actually gets us.
And what we'll do is today, spend some time in particular
on what the sample code is that Apple provides not
because it's interesting but because it's representative
of how you might write your own applications.
So, here we have a-- knowing a number of prompts,
I'm going to go ahead and just call this test.
My organization name can be whatever I want here.
I'll say Harvard University.
Company identifier, you just need a probabilistically unique
string really so that if you push an app
to the app store it's distinct.
We'll go with edu.harvard which is a common paradigm
in the Java world for packaged names.
If we own harvard.edu, presumably no one else
in the world is going to use that same prefix
for their applications but it's just a human convention.
Class prefix, I'm going to leave blank 'cause it doesn't matter.
Devices, for lecture I'm going
to typically choose iPhone really just
so that it fits nicely in the screen,
so we can see everything.
And then there's a few options.
Here core data we'll come back to in the future but it has
to do with an abstraction layer for storing data
in the equivalence of a database.
Use automatic reference counting,
is that memory management feature,
I alluded to earlier having coming out a couple
of years ago, it makes our lives easier.
So, we'll leave that on.
And then, include unit test, so I'll uncheck those for now
but we'll come back to that in time as to how
to right tests for your own code.
I'm going to go ahead and click next now.
It's asking me where to save it.
I'm just going to save it wherever, on my desktop for now.
For source control, just to keep my directory simple,
I'm going to uncheck that for now,
by all means you use the built-in GIT functionality
for doing version control and we'll defer to any number
of online tutorials for how to use that in Xcode itself, yeah.
[ Inaudible Remark ]
>> Good question.
You have to adopt your code a lot.
If you're developing for iPhones and iPads, it really depends
on your application and to what extent you want the user
interface to just grow to fit or to rearrange itself somewhat.
For instance, if you don't implement a different view
for the iPad specifically, what Apple does
by default is it shows you your iPhone view.
But, in a tiny subset of the window
and they do give you a 2X button to zoom in
but most every application I've ever seen
that just relies on that looks awful.
So, you would typically want as a developer
to somehow customize your interface even if it's just
by providing higher resolution graphics for the bigger device
so that it doesn't look like someone just zoomed
in on your application.
But short answer, it depends,
and because of MVC it's actually relatively easy
by not changing the essence of your program,
just designing a new view that has similarly named variables,
so to speak, to hook into your data.
All right, so now, I'm going to click Create
and let's start poking around Xcode.
And let me go ahead and hide some distractions
for just a moment and here we have, let me move this
so that everything is in view on the screen here.
Here's everything we have to begin with.
I'm going to wave my hand at all of these stuff in the middle
because generally you can dive right in without having
to change any of those configuration details.
And this is the stuff that's nice to get for free
out of the box rather than opening up something
like TextEdit and just starting to write Objective-C code or Vim
or Emacs or whatever your preferred text editor is.
Xcode just sets up a whole bunch of defaults for you.
So, let's instead focus our attention on the files
that you get for free with an application,
but before we do that,
let me zoom in on the top left hand side of the screen.
Notice that Xcode is so user friendly, it's just like iTunes
to run my program, all I do is click Play.
And if I go and do that, build succeeded.
What's happening
in the background is my iPhone application is launched
in the software based simulator and voila,
I'm now an iPhone programmer.
So, really that's all it takes to make an iPhone app
and I'm sure back in the day, I mean, there have been stories
as an aside where you-- someone made like a ruby app was it
which was just a stupid JPEG of a ruby, the gem, submitted it
to the app store, put a price of like-- you maybe recall this,
a thousand dollars and like four people actually bought it.
And it was really just an image of a glistening gem.
So, it was that easy for that person to make that application.
So, this could be you next.
So, what's actually going on underneath the hood?
Well, let's just notice we've got a white background,
we still have the status bar at the top,
so there's still some built-in functionality there.
And if I minimize it by going like that,
there indeed is my test application
on the desktop of my iPhone.
So, let's look at what files made
that possible uninteresting though this application is.
So, I'm going to expand these folders.
As an aside, they're not necessarily folders in reality.
They look like folders but they're technically groups,
which means if you poke around the hard drive of my laptop,
you won't necessarily see those same yellow folders.
All the files might actually be in one big folder together.
So, this is just an illusion for organizing your code
like you might in Eclipse or something similar.
All right, so it's kind
of overwhelming how much stuff there is.
So, let's start ignoring some of these things quickly.
So, at the bottom under products is Test.app.
This is just a-- I'm the only one that can see that.
So, at the bottom of the screen here is Test.app.
That refers to the program
that [inaudible] play button I already installed
on to my phone.
So, that's the compiled application.
So, it's not interesting beyond the fact that it exists.
Now, let's close that to avoid the distraction.
Under Frameworks, I see UIKit, Foundation, Core Graphics.
Which of those have we seen or mentioned before?
>> Foundation.
>> So, Foundation.
So, we saw that last week, we saw that earlier in some
of our Objective-C code.
That simply had a reference in the import line to some library
that someone else wrote with a whole bunch of functionality,
whole bunch of classes and method that I don't have
to worry about, I can just use them
without implementing them myself.
We also heard verbally UIKit.
So, it's inside this library that we're about to get all
of the interesting functionality that gives me buttons
and text fields and things I can touch and click on,
on the glass of a screen.
And Core Graphics we won't use today but this refers
to a two-dimensional graphics library
with which we can draw squares and rectangles
and more interesting things on the screen.
So, let's collapse that and ignore.
Now, we have some pings, so, Default@2X,
Default.png, Default 568h@2X.png.
Does anyone know what these are?
Yeah. Images for?
[ Inaudible Remark ]
Exactly. So, there's some default images
that if you read the documentation must be named
exactly this that you could override them
if you really want it.
And these are just the images that the user sees
as your application boots off.
Now, for-- or an application like this,
we barely even saw them because the thing loaded so fast.
But if you have a network based application, a game that logs
into some game server, you might have a couple of seconds
of latency while the program loads.
This is where you'd see the Angry Birds splash screen
or something similar like that.
So, it's just a convention, they're not really interesting.
For our purposes, Apple gives them to us for free.
So, let's ignore them hereafter.
Test Prefix.pch.
This is a precompiled header which just means a file
that will do some stuff for us that will never again,
at least for the next several weeks have to think about.
In this case it has to do with some backwards compatibility,
but it's just some additional metadata that Apple uses
to bootstrap a program with our--
without our having to write this.
So, I'm also going to ignore that.
So, we're really whittling this down to the essence.
I'm going to skip main.m because that's clearly of interest.
Test-Info.plist, this is like a preferences file.
A plist is a property list.
This is just an XML file underneath the hood,
a whole bunch of tags and values and attributes and the
like similar to what you might have seen with Ajax
in the world of DOM, in HTML 5.
Xcode is simply reading that XML file and showing it to us
in this very pretty fashion, with rows and columns
but it's just an XML file underneath the hood.
This is a GUI with which to edit it.
I'm not going to change any of these things now
but you can kind of infer from the names
of the XML elements here what kinds of things you can tweak,
what interface orientations you support, up-down, down-up,
left-right, right-left,
those sorts of things can all be configured by a--
by a point and click by editing this kind of file.
But we'll stick with the defaults for now.
If we go back to the directory structure
over here, infoplist.strings.
So, we'll come back to this perhaps in the future
but this makes it easy for us to localize our application.
What does that mean?
>> Translating to other languages?
>> Yeah, exactly, translating it to other languages.
So, we won't expect you to support more than just English
for the staff's choice of projects but this is
where you could define some key value pairs where the keys are
like constants that you use in your actual code
that represent the words you want your program
to actually display.
And based on whether the user's device is in Spanish mode
or Chinese mode or English mode,
a different plist file will be loaded containing those strings
and used on the interface for your native speaker.
So, it's a nice way of factoring out all of the words
for a program and putting it--
sorry, not in a plist but into a dot strings file
which is essentially just a text file.
So, that leaves only three files of genuine interest.
So, let's dive into main.m, and it looks, hopefully,
a little familiar, some new stuff but mostly boilerplate.
So, let's zoom in.
At the top, we have a whole bunch of comments
that are outputted automatically by Xcode depending
on how I've configured the program
when I first installed it.
First line of interest is import.
This is apparently giving me access to what kind
of functionality, that import line?
Sorry? So, UIKit, so user interface related stuff.
This is allowing me to write a graphics-based application
as opposed to the command line stuff you guys did last week
with Rob.
Import AppDelegate.h, don't know what that is yet,
but I remember seeing it among the remaining files,
so we'll come back to that in a moment.
That's a file that I get to actually interact with.
Here's the promised signature for main,
we're not going to touch this.
Here's autorelease pool, and the only thing that's a little
different now is that apparently main's sole purpose in life
in an iOS application is to return,
whatever the return value is,
of a function called UIApplicationMain passing
in its argument count, so whatever was typed
at the command line,
which probably has no significance unless you override
some of the default settings in Xcode,
passing an argv, same thing.
Nil, whatever that is, it's essentially null
but with some magic around it.
And then lastly, let me scroll to the right,
it's a little long, this string, and it's wrapping,
NSStringFromClass AppDelegate class.
So let me see if I can avoid the wrapping
by shrinking the window a little bit.
So here we go.
We are returning, whatever the return value is
of UIApplicationMain passing in these three things
which don't look very noteworthy.
The interesting one seems to be this last one.
That's effectively passing in a reference
to a class named AppDelegate.
So this one line of code is what's used in the iOS world
to hand off control, either briefly or for quite some time,
for main to a different class, that class being AppDelegate,
and it's apt-- aptly named in that we are going
to delegate control of my application
to a guy named AppDelegate, so that's the class that I,
the programmer, apparently should start writing
if it doesn't exist just yet.
And as soon as AppDelegate is done, apparently, main wraps up,
my program quits and returns by default,
it's not there explicitly, zero.
So this is how we make this leap from main.m
to whatever my higher level iOS application is.
So we'll never again really need to look at this file, you--
can't think of any instances in the next three weeks
where you'd even want to touch this file.
So I'm going to close supporting files all together and leave us
with just two files now to glance at.
>>What would this mean?
It's a C function, right?
>> UIApplicationMain, it's a-- sure C function, yes.
Happens to be capitalized but it's a function, not a method.
All right, so when looking at files for the first time,
I would generally suggest to start with the dot H file,
in part 'cause it's simpler, usually shorter,
and also because it's often more descriptive.
So let's start there.
And indeed it is short, let's see what's going on.
A whole bunch of comments at top.
I'm importing the UIKit again
so that apparently my class can have access
to its functionality.
And now we see a similar construct to what you saw
with Rob last week
and we recapped a bit ago @interface AppDelegate colon
UIResponder open bracket UIApplicationDelegate
close bracket.
So let's try start translating this
into slightly less technical English.
What does that one line of code do?
Yeah?
>> It says child UIResponder?
>> OK, it says what's a child of UIResponder?
>> The AppDelegate.
>> OK. It says that the class called AppDelegate is a child
of UIResponder.
Good. And what else?
>> It adheres to the UIApplicationDelegate.
>> And it adheres to the UIApplicationDelegate,
and I'll scroll to the right to confirm protocol.
So what does that mean?
It means, not only does it behave much
like a UIResponder object does, no idea what that is,
but it sounds like something Apple wrote 'cause it starts
with UI, part of UIKit.
And UIApplicationDelegate is apparently a set of methods
that Apple says I have to implement
if I implement that protocol.
Now this for the most part is copy-paste.
We won't be so presumptuous as to change these defaults,
we'll typically isolate the code that we write else
to other files or subsets thereof
or to new files of our own.
But let's focus on one other detail.
Inside of this class definition for the AppDelegate class,
there's also a property.
What was a property?
Yeah?
>> That's the getter and the setter automatically.
>> Yeah. Exactly.
It allowed us to synthesize, so to speak, a getter and a setter
for ourselves automatically, in other words,
to provide programmatic access, functional access
to what's typically an individual instance variable.
And what's useful about this is
that you can specify some attributes for those setters
and getters and we'll see these in more detail,
before long, but non-atomic.
Just means, hey Xcode, when you generate that getter and setter
for the property called window,
don't bother writing thread-safe code,
and by thread-safe I mean a whole bunch
of special synchronization related code to make sure
that only one person can call this function at any given time.
The reality is, it's just not going to happen.
By convention, this does not need to be atomic code
and by specifying that it should be non-atomic,
it makes the getter and/or setter faster.
So we'll-- we won't see in the coming weeks really an instance
where you need atomic, and technically it's there just
because atomic is the default, and I want my getter and setter
to perform ever so slightly faster even though we humans
would never notice.
[ Inaudible Remark ]
Good question, are they open source.
You can see the header files, the dot H files,
but to my knowledge not to the actual implementation files,
at least not from recent versions of iOS.
There may very well be older versions floating around.
All we get is the compiled versions of those files
and the header files which are readable.
All right.
>> Question.
>> Yes.
>> Can you give us an example
of when you would have to use the atomic?
>> If you are writing a--
when would you use atomic as an attribute?
If you are writing code that require--
that supports multiple threads, so two things happening at once,
and each of those threads might want to access some value.
So, let me contrive an example offhand.
So, iOS now supports printing capabilities.
So for instance, if you had some program that allows you
to print your notes for instance,
in the notes application.
If the notes application were multithreaded,
so could do two things at once, and one of those things happen
to be printing and another thing happen to be editing,
which surely the notes application supports.
If the printing application, the printing feature,
needed to read the contents of your note, the contents
of your note might be implemented by way
of an instance variable and accessed by way of a getter
and setter implemented as a property.
Meanwhile, I the human, with my fingers,
might want to actually be editing that same note
and therefore the editing feature might also need
to read and/or write, get and/or set that instance variable
through this property.
And it's probably not a good thing
if I allow both the printing functionality
and the editing functionality to look at the value and change
that value at the same time.
Because I might say print now, make some changes,
and all of a sudden, my printer starts printing out part
of the old version and part of the new version,
unless I've somehow locked access to that file.
So it's contrived in the sense that you can do things so fast
that humans-- that's not going to happen,
and you can make a copy in theory of the instance variable
and avoid that problem all together,
but that's the spirit of it.
If two things might simultaneously try
to read and/or write the same value, bad things can happen,
like garbled printouts in that case.
Yes.
[ Inaudible Remark ]
Read-only.
Read-only is another.
Read-only gives you a getter but no setter.
Good question.
And strong, this one is easy--
more easily explained in the future after some number
of examples because it refers to memory management, in particular
that automatic reference counting feature
that I alluded to earlier.
And we'll see this in the context of some GUIs
that we actually start programming.
So well that will-- we will revisit.
All right, so applica--
AppDelegate.m is the last place for this program.
And recall that this program only loaded a white screen.
So all of this effort just to load a white screen,
but we'll see in our next example
that you can do much more
with relatively little additional effort.
So this file is a little overwhelming,
but thanks to the green lines here,
turns out it's mostly comments.
So it's just boilerplate code that Apple provides
and we can actually delete most of this just to simplify.
So let me zoom out just to get the lay of the land.
On the top of the file we have some comments.
I'm importing AppDelegate.h,
so AppDelegate.m is importing AppDelegate.h, common paradigm
for the methods file to import the header file.
@implementation AppDelegate, what does this mean?
Translate that one line of code.
What's that line of code telling Xcode?
Yeah?
[ Inaudible Remark ]
Exactly. Here comes the implementation
of the class called AppDelegate which was declared
in the file called AppDelegate.h. So this func--
this method is hugely named application--
actually, good opportunity for review.
What is the name of this method?
Or more precisely, what is the name of the selector?
Yes?
[ Inaudible Remark ]
Good, good.
And as humans we typically wouldn't say the colons
but that's exactly right.
They're part of the name of the method.
So, applicationDidFinish
LaunchingWithOption.
So, Objective-C recall supports essentially some variants
of named parameters where they're not named in the sense
that they appear inside of parenthesis as might be common
as key value pairs or as JSON objects in the world
of JavaScript programming.
But the names of methods in Objective-C are meant in spirit
to read like, frankly full out sentences,
so they do exactly what they say.
So, what does this one do?
I honestly have no idea at firs glance.
It seems to be code that someone else wrote.
Indeed Apple put it in this template for me.
But then there's a few lines of implementation inside of it.
Let's take a look here.
Self.window gets UIWindow alloc initWithFrame UIScreen
mainScreen bounds.
All right.
This looks like probably the most complex line
of Objective-C code we've seen thus far,
but it's really just the combination
of very simple building blocks.
So someone on the left hand side,
what is self.window referring to?
What is that?
>> It is a window.
>> It's referring to these programs Window.
And how about more technically underneath the hood?
What is self.window, W-I-N-D-O-W, referring to?
[ Inaudible Remark ]
Close.
>> The property.
So Window, recall, was the name of the property
that we saw on what file?
>> AppDelegate.h.
>> AppDelegate.h. So we declare the property called Window.
And that property was of what type?
>> UIWindow.
>> It was of type UIWindow, capital U-I-W window.
OK, and it was a star which means a pointer there, too.
So self.window and again, for those following along
at home here with laptops, feel free to download the source code
from the [inaudible] website so you can toggle back
and forth among these files if you would like.
So self.window is effectively invoking a method--
which method?
>> Setter.
>> The setter.
So this is one of these pieces of syntactic sugar
that you get with Objective-C.
We could implement this same line of code
by literally calling set window as the setter method
that we get automatically by declaring a property.
But one of the purposes of properties
in Objective-C is just to simplify our code
so that we don't have these damn square brackets all
over the place in very traditional method calls.
It's just so much more readable just like in JavaScript
to have this dot notation and then an assignment operator,
the equal sign right next to it
which effectively invokes that setter.
But it's syntactic sugar in that underneath the hood,
this is just a message being passed
to an object to set some value.
But it reads much more clearly this way.
Self.window is going to be assigned what value?
All right, so will someone else, what does this chunk
of highlighted code do for us?
[ Inaudible Remark ]
OK, it allocates a UIWindow object.
I don't really know what that is just yet but it sounds
like something that's useful to have,
a window for my application so I'm allocating it.
I'm not calling init though,
I'm calling a slightly differently named func--
method, initWithFrame, and this again is largely a human iOS
convention or Objective-C convention.
Init is typically the default method that you call
to initialize an object.
But if it makes sense programmatically
to initialize an object with some arguments,
the convention is to call it I-N-I-T then capital letter
of whatever it is you're adding to the object.
So use [inaudible] case.
And initWithFrame, I don't know what a frame really is
but it seems to be related to the screen
and the screen's bound.
So let's look to the right hand side there.
The value of this argument, so to speak,
is going to be the result of what?
Calling UIScreen mainScreen.
So I'm not calling alloc here.
Turns out this is a class method called mainScreen
that apparently, if we read the documentation,
is returning effectively a pointer to an object
of type UIScreen that represents the only screen on my device.
So the screen is-- you think of it as the glass.
Meanwhile, that glass is a fixed size,
so when I pass the message called bounds
to this UIScreen object, what do you think bounds returns?
>> Dimensions.
>> Yeah, the dimensions.
The height and the width, effectively, which is going
to be a little different if it's an iPhone3 or an iPhone 4S
or an iPhone5, depends on the device, or an iPad,
depends on the device potentially.
And so this is a programmatic way of getting myself a UIWindow
which we'll see is like a container.
It's just a special UIView.
It's the parent of all other view related objects
on my application.
I'm just initializing it dynamically so I don't even have
to know in advance what size of screen this is going
to support necessarily.
So, a long winded way
of explaining just how you get access to a Window
which again is going to be a big rectangle
that we can start putting all of our buttons and text fields
and keyboards and all of that on the screen.
Now, this is just a comment.
Override point for customization after application launch.
So this is just someone at Apple wrote this comment for the rest
of the world to just kind of know
where we could start plugging in code of our own.
And we'll get to that.
But now, let's see what happens after.
Why is this program's background white?
Apparently 'cause of line three here,
self.window.backgroundColor gets UIColor whiteColor.
So here, too, we have some conventions.
Self.window is the property.
That's referring to my window object, whatever that is.
It's a rectangle, a canvas on which we'll paint other objects.
Dot backgroundColor, this too is a property,
and I know that because of the fact
that there's a dot there, honestly.
That's my clue that this is another property associated
with that object.
And meanwhile, UIColor I'm going to guess is a class just
because it's capital U, capital I,
capital C that's following the conventions
that Apple has for class names.
What kind of method is whiteColor apparently?
>> Class method.
>> So it appears to be a class method
because if UIColor is a class and we're not calling alloc,
the only other way to talk to a class
without having an object is through a class method so you--
or whiteColor is apparently a predefined message
that I can send to the UIColor class
and get back some representation of white
and maybe it's effectively a number like FFFFFF.
It's something like that that represents the color white,
however Apple implements it.
Now, I'm getting a little tired of taking myself for--
taking my own word for it, so let me try a little trick
of Xcode here to start digging in.
If I go and hover over UIColor, let me zoom back in,
while holding option, notice that this is clearly a keyword
of interest and notice that my cursor has become a
question mark.
So this is one of the nice features honestly about X code.
It's probably of all the IDEs I've used, Elipse and NetBeans
and others, it's honestly probably the best.
It's unfortunately pretty much designed only
for Apple programming.
But it's a really nice IDE in part
because it's very instructive.
So if I now click on UIColor, notice that I'm going
to get a little pop-up and a lot of IDEs have this,
so this isn't something too new, but I get a nice description.
A UIColor object represents color
and sometimes opacity, dot, dot, dot.
It's been available for quite some time
since iOS 2, so several years ago.
It's declared in a file called UIColor.h. So an answer
to your question, you can't see the actual implementation
of this but I can see the header file and any constants
or methods or other things related.
Here's what's of interest.
The Apple documentation is actually pretty darn good.
So if I click on UI class reference,
UIColor class reference, this program called organizer loads,
but the same-- this is just an embedded webpage.
It's an embedded Safari instance
so the same documentation is available on Google and just
to confirm as much, let me do UIColor reference.
Sure enough, first hit is on developer.apple.com,
and that's the same exact page.
So realize you don't even need X code to poke around.
So let me increase the font size and poke around here.
There's a few things to keep in mind
when navigating Apple's documentation,
and we won't do this ad nauseam.
Let's just use UIColor as a simple example
of how to navigate the docs.
It inherits from NSObject.
So that's kind of cool.
We've seen how to do that in code.
This is just the documentation's way of saying it.
Conforms to-- conforms to what?
What's-- what are those three blue words apparently
examples of?
Those are three protocols.
NSCopying we've seen, turns out there's other things, NSCoding,
NSObject, whatever that is.
If I clicked on them, I could learn more,
but I'm not too interested in that just now.
This is part of the UIKit framework,
but we kind of guessed that earlier from the UI prefix.
Declared in, all right, somewhat interesting.
Sample code, so this is
where I've never been a fan of Apple's code.
A lot of their sample projects are way overcomplicated
for newbies.
So I would generally advise not diving into something
like a courts demo which is a fairly sophisticated graphics
demonstration and looking instead to online tutorials
or books or the course's own sample code,
'cause I think you'll often find Apple's code overwhelming.
But feel free to poke around if you'd like.
And now, here's some standard vanilla stuff.
So, some English prose explaining what it is.
For some reason, Apple calls methods tasks
in the documentation but tasks just means methods.
The ones that are prefixed
with a plus means they are what types of method?
Class methods.
You can call them without instantiating an object.
With alloc, the minus symbol [inaudible] fix means it's an
instance method.
So you have to allocate the object first.
Apple does not exactly alphabetize them.
They essentially categorize them into some arbitrary
but generally helpful categories creating a UIColor object
from component values initializing.
So honestly, Command-F will be your friend quite often.
When you're looking for something that you remember part
of the name but you can't quite think of it,
reading through the documentation can be a little
tedious because of the arbitrary way they sort and,
I mean there is absolutely no sort order
to this thing is best that I can tell.
But there is white color.
So if we click on white color, notice that it's also a plus,
so it's not a property.
It's a method that gets passed to an object,
message that gets passed to an object
and there is its documentation and let's treat--
consider this as representative of the rest of the docs.
Returns the color object whose gray scale value is 1.0
and whose alpha value which refers to opacity is also 1.0.
So that's the FFFFFF that I referred to you earlier.
Return value of this method is the UIColor object.
Where it's available, not too interesting.
And then we get yellow and some other standard colors.
And if we really wanted to, we could mix together any colors
of the rainbow that we want, but you get some standard ones
out of the box just 'cause it's convenient, nothing else.
So, just a couple of lines left before we are indeed
iOS programmers.
So, let's zoom back in.
This last line before the return statement is important
and you can probably maybe guess what it is,
self.window makeKeyAndVisible.
So first, what is makeKeyAndVisible?
Not what it does, just what is it?
It's another example of a-- of a message or a method,
a message that's being passed to an object or a method invocation
to put it differently.
So makeKeyAndVisible.
I don't really know what key is
but visible presumably means make the window visible.
Perhaps by default it's hidden, much like you might have
with CSS hidden divs and what not in JavaScript,
so it's apparently hidden by default.
We want to show it.
Key? Key just means make it the key,
make it the important window that responds
to the user's key presses by default.
Make key window makes it foregrounded effectively.
So return, and this is one
of the stupider things of Objective-C.
Whereas the rest of the world uses zero or one or true
or false, objective C uses YES or NO, in all caps.
It's just a Boolean value.
Return YES means return success in this particular case.
Now, thankfully we can delete the rest of this file
because down here is a method.
I'll let someone else answer.
What's the name of this highlighted method?
>> ApplicationWillResignActive colon UIApplications
star application.
>> Too much, you consumed too much of the string.
It's just UIWillResignActive.
And if you're writing it out, include the colon.
But the name of this method
or this message is ApplicationWillResignActive.
If I actually read this-- the comments, it will explain
in more detail what it does.
But in a nutshell, this is a method
that will be invoked automatically
by the operating system when my application, as implemented
in my AppDelegate class, is about to do what?
Resign active state.
So it's when the user has hit the button
but nothing has quite happened yet.
So that's my way of responding.
So think again about JavaScript and DOM events,
things like onkeydown, onkeyup, onsubmit, onchange,
all of these event handlers, very similar in spirit,
whereas those event handlers in JavaScript are called onsubmit,
onclick, onkeyup and so forth, in Object-C,
they're a little more-- they're--
in iOS, they're named more verbosely
but it's the same idea.
These are event handlers that are being invoked for me
by the operating system.
What's another?
ApplicationDidEnterBackground,
so when the thing has actually been backgrounded.
ApplicationWillEnterForeground.
So just before it appears on the screen, maybe I want
to update the inbox so that the user sees the current inbox not
the old one, that what might have been the case
when they backgrounded it a day ago.
ApplicationDidBecomeActive, so once it's actually running
in the foreground, application will terminate.
If the user holds down the button and clicks the X
on an icon, you do have a chance
to do some last minute housekeeping before they even
force quit their application.
So these are all hooks into these very low level operations.
Notice that there are comments inside of them
but nothing is actually happening,
I can actually safely delete all of them.
That won't break the class
because what class does AppDelegate descend from?
UIResponder.
So if I actually dig a little deeper,
it turns out that those methods are probably implemented
elsewhere, higher in this class hierarchy for me.
So even though the templates
that Apple provides often have lots and lots of code,
a lot of it just to kind of focus
and simplify things you can start deleting at least
if there's no built-in functionality there.
And in all of the lecture examples tonight,
I've done that in advance.
As you'll see I've pruned away anything that's superfluous
so we can only focus on what's core to those applications.
So incredibly underwhelming.
Before we take a break, let's at least reassure
that we can do more interesting things.
I'm going to go ahead and rapidly create a new project.
Single view applications, 'cause this time I want a view,
I want something on the damn screen.
I'm going to call this Test2, but we'll come back
with more interesting examples.
I'm going to uncheck used storyboards
for now, more on that to come.
I'm going to click next.
I'm going to go ahead and save it on my desktop.
I am now going to notice but explain later a few new files,
ViewController, that's good, we have some brains
for my application now.
But also this xib file pronounced of course nib, N-I-B,
for historical reasons.
When-- as soon as the nib file became an XML file,
they renamed it xib, but we still say nib.
Now notice nib or dot xib,
this makes programming look fun now all of a sudden.
This loads what's effectively a tool called Interface Builder,
although Apple doesn't really call it
that anymore 'cause it's embedded right
into Xcode itself.
This is how easy it's going to be to start making
at least the simplest of application's UIs.
I'm going to go to my little palette here,
on the right hand side and notice
that there's some juicy friendly-looking stuff
down here, label, rounded rectangular button,
segmented control, slider, switch, progress view,
so some familiar UI mechanisms.
I'm going to do a super simple one like label.
I'm going to drop it over here,
roughly in the let's say top middle of the screen.
I'm going to say hello class.
OK, it's still centered.
Now I'm going to click the run button at top left
which will launch the simulator and if all is well,
now we have the beginnings of a more interesting application.
So let's take a five-minute break here, we'll come back
and actually see how to make that and more.
All right we are back,
so the exciting cliffhanger before we took a break was
to get hello class on to the screen.
But before we forge ahead
and reveal just how this magic happens, any questions
about Objective-C, UIKit or anything thus far.
Really? OK.
>> What is this little bar at the bottom, the red rectangle,
red rectangle, green [inaudible]?
>>Red rectangle--
[ Inaudible Remark ]
On yours.
>> It's all-- it should be on hold.
>> Let me see if I can replicate that.
Let's see, how did you get that on to your--
you have it at the bottom of the UIView?
>> Yeah. It's sitting on the bottom.
>> Yeah, it's a good question, it has to do with hooks.
They're similar in spirit to these, which we will talk
about that allow you to drag and drop more easily
on to the surface of this object.
We don't have much in this.
Let's see, click here.
I am not sure where that feature has been tucked away,
I will try to replicate it after and we can look at it
at your-- on your screen.
OK. Yup?
>> I have something called storyboard instead of--
>> That's because when you created your project
for single view application, you left Use Storyboards checked,
and we'll come back to that.
But for now I thought I'd simplify and uncheck that.
>> OK.
>> If you'd like to re follow those steps.
All right.
So we are back now with the single view application
and we seem to have a couple of more files.
We still have an AppDelegate we still have an AppDelegate.h
and .m specifically but we've got at least three new files.
And just in case there's even more going
on underneath the hood, let's zoom in on these groups,
these folders over here.
Those files look familiar.
I don't think there's anything new in there.
The file is called Test2 instead of Test now
but that's 'cause I renamed my project.
So all of these looks familiar,
nothing else is new underneath the hood.
And indeed if we look at main.m, there's nothing new there,
it's still called AppDelegate
and somehow that's kicking off this process.
So let's ignore those supporting files.
And let's go into AppDelegate.h to see what's new here.
Let me hide this window on the right hand side for simplicity.
And does anything jump out at you as new in this example
versus the empty application we wrote first.
Yeah. There's a view controller.
So this is interesting, we have two properties, not one,
and we needed that original property window just
so that we had something to hang
on to somehow called the UIWindow and it was assigned
to that property in AppDelegate.m.
But now we've got another property also strong
and non-atomic, which for now just take on faith as copy-paste
when you declare a property like this.
It's apparently a pointer called viewController, lower case v,
and it points to an object of type ViewController,
capital V. So I don't quite know what that is in terms
of iOS's worlds but view controller, it's a controller
which was what, in general terms?
What's the view controller?
What's a controller?
>> Brain.
>> Brain of the [inaudible].
>> Yeah, so it's the brains of the operation.
So MVC, so recall one paradigm, let's see-- let's really--
give me at least one chance to swipe.
All right.
So we had this picture over here, MVC.
So, the view controller in the world
of iOS is just the c in MVC.
So it's the brains of our application.
Now in reality, as you get your--
you start writing more and more complex applications,
you might very well have more than one view controller,
more than just one C and you might have a super important
controller that somehow delegates control among other
controllers but it's still the brains
of the operation ultimately.
So let's dive into the H file as should be common technique
to just see what's going on inside of ViewController.h.
That is very underwhelming.
So my ViewController class is apparently a child
of the UIViewController class and that's where the story ends.
There's nothing going on at least inside of the H file.
So let's take a look at AppDelegate.m before we look
at that other method file.
What else is new here?
Well, I'm a little overwhelmed by all the lines here
but I realized that, oh, almost all of these is comments.
So for simplicity, let me go ahead and throw away everything
that looks uninteresting in this template and zoom in only
on the code that remains.
Now this first line, self.window,
this looks familiar, right?
It's a little verbose but it allocated a UIWindow,
figured out its dimensions and gave me a pointer there too
by storing it in my window property.
OK, so something to hang
on to even though we didn't do anything interesting
with it yet.
Now, what line of code is new
in this method called application
didFinishLaunchingWithOptions?
Yeah, self.viewController.
So here is something interesting.
Even though this application only puts hello class
on the screen, this line of code looks new.
So self.viewController is referring to what?
To be clear.
Say again?
[ Inaudible Remark ]
The ViewController property.
So self.viewController is the property
that was declared in what file?
AppDelegate.h, exactly.
So we're assigning to that property the return value
of this expression here.
So a little bit of this is new, ViewController alloc.
So alloc allocates me a new object of type ViewController.
Who wrote the ViewController class?
[ Inaudible Remark ]
Apple, at least in the form of the template code, but they seem
to have given me the raw source code
for the ViewController class as we just saw
from the ViewController.h. So I can take
over the brains of this operation.
They did not give me the source code for UIViewController.
But that's fine 'cause my ViewController class can still
descend from it in terms of a hierarchy.
It can be my parent nonetheless.
So give me a ViewController object
and then initialize it with nib name.
So here we see the N for nib
for again historical reasons, but nib name.
A nib is at the end of the day just an XML file.
But it's not an XML file we will ever look at.
You can but it's just not interesting
and it's rather overwhelming.
A nib file is just a file that stores the result
of creating a user interface, using Xcode by dragging
and dropping widgets like I did earlier.
I drag the simplest of them just to label
but I could start dragging as you saw sliders and knobs
and switches and text fields and other such things.
A nib file just stores that result of all that dragging
and dropping so that you can program
at least your UI a little more easily.
Now you don't have to program your UI with Xcode in that way.
We'll see it and do it in much more manual way.
But what this does is it initializes my view controller
with the contents of a file called nib name is
new controller.
If I read the documentation, I will see that that method,
initWithNibName is supposed to look
for by default the string that's in quotes dot XIB.
So that's how I'm linking my code in Objective-C
to what we call the nib file earlier which again I got
for free via this template.
So that's where my code is saying,
give me a view controller and initialize it
with the contents of that XML file.
So in other words if I wrote, if I created
that user interface a week ago by dragging and dropping labels
and text fields and sliders a week ago and saved it,
this reloads it into the program's memory.
So, lastly, another new line, self.window.rootViewController.
We didn't have this before
because we didn't have a controller.
Our program was so simple there were no brains behind the scenes
'cause it only showed a white screen.
But it turns out there is a property called
rootViewController whose purpose in life is to serve
as exactly that, the most important view controller,
the most important C controller that runs the entire operation.
Now how do I know that's the case?
Again, you don't have to take all of this on faith.
Let me hover over self dot--
whoops, let me hover over self.window,
a question mark appears.
And, oh, interesting.
This is a property called window that's been declared in there.
And I want to see the documentation, so let me go
to the reference down at the bottom.
And now the reference for the window--
there's a whole bunch of stuff, and if I skim,
skim, skim, skim, root.
Mine is the only phone connected to the speakers in the room, OK.
So if I skim through here, property is window.
Oh, you know what, I'm in the wrong place.
Because if this is the UIWindow, I'm currently
in the UIApplicationDelegate reference
which just means again my AppDelegate implements
that thing.
So what I actually want to go to.
Let's do that trick from earlier, UIWindow,
and there sure enough, let's make sure we get
to the iOS version and not the Mac OS version.
So let's add iOS there.
UIWindow class reference.
And now if I scroll down tasks which again our methods.
Keywindow, we haven't seen that before, but it sounds
like the buzz word we saw earlier and aha,
there is the formal documentation
that says a UIWindow, which is what my window property points
to, has a property called rootViewController.
And if I read the documentation,
the root view controller provides the content view
of the window.
Assigning a view controller to this property dat dat da,
installs the view controller's view
as the content view dat dat da.
This is how you specify who the brains are behind your
application, and it's going to be specifically an instance
of my view controller class.
So, the only two lines here then that are new are these,
the only files that are new or the three up there.
So there's one file we haven't looked at
yet which is ViewController.m.
So the implementation of this class.
So looks like fortunately just some template code.
And in fact I can delete all of these.
So let's see what's in here of interest potentially.
I've got a @interface sign
at the top ViewController open parens and then end.
This feels weird because where do I usually see @interface?
So in the header file.
But I already saw this in the header file.
Just to be clear, if we go back to ViewController.h,
I already have, excuse me, @interface ViewController.
So what is this doing here?
[ Inaudible Remark ]
What's that?
Yeah, it's sort of a private interface.
It's using what appears to be a-- what's the buzz word here?
A feature of the language known as a category, yet turns out--
and this was something added somewhat recently,
you can have nameless categories with no name,
open paren, close paren.
So this is a category which just means here--
hey, Xcode, here comes some more methods that are associated
with the ViewController class.
Now it turns out this is just boilerplate code
that Apple has provided a starting point.
There are no such methods but if I wanted to have private methods
that I don't inform the world
about via my header file, where do I put them?
Where that blank line is right there.
But functionally, this isn't doing anything for me,
it's kind of overwhelming me.
So I'm just going to get rid of it with no effect.
@implementation is what I did expect to see in this file,
and now there're two methods that we did not see before.
And they're not arbitrary.
It turns out that viewDidLoad
and didReceiveMemoryWarning are methods defined
by Apple in what class?
They're not in my class because, right,
if I go to my header file, I made no commitment
to implementing those two.
So where do viewDidLoad
and didReceiveMemoryWarning come from?
Yeah. Yeah.
Must come from some parent or ancestor class, and I'm going
to guess it's from UIViewController.
And if we actually looked at the documentation there,
maybe followed some links,
hopefully we would indeed see the definitions
or the declarations of those methods in the documentation.
Now what do they do?
Thankfully, there is an upside to the verboseness
of all these method names.
ViewDidLoad, that method is invoked when the view did load.
And what's the view, just to recap?
What is the view with respect to an application?
The interface.
So when some stuff came up on the screen,
what method gets called?
That one. Why might that be of interest?
Well, once the stuff has been painted on the screen,
the text fields and the sliders and whatnot, maybe you want
to start updating the values.
Maybe you want to start bouncing a ball
around once the UI has been generated for your game.
Whatever you might want to do could happen at that juncture.
And so Apple's comment here says, do any additional set
up after loading the view typically from a nib.
So this just means especially if your interface came
from a serialized XML file.
So just a nib file that you created with the drag
and drop interface we saw briefly earlier,
you can from this method do more stuff once
that UI has been reconstructed into your program.
Now super.
For those unfamiliar, less familiar, what's that line
of code doing above the comment?
Yeah.
[ Inaudible Remark ]
Exactly, that line of code is calling--
passing the viewDidLoad message to the super class
which is the parent object of this particular class.
Now this too is a convention,
and if you read the documentation, Apple will say,
"if you implement viewDid Load, you had better remember
to call our version of this method
in case there are some important stuff that happens
in this class hierarchy, after which you can do your thing.
So I'm fine with deleting the whole method
because if I delete it, it will still exist where?
In the parent class.
What I should not do is ever get into this habit,
which means my object might not be properly loaded
if I have not called the parent class' implementations
of the same method.
So, again, you know that really by convention
and from reading the documentation carefully.
But viewDidLoad, don't need it.
DidReceiveMemoryWarning, I'm not going to need this one either
so I'll delete, but you can probably guess what this means.
If your iPhone has a limited amount of memory, which it does,
and you start loading lots and lots of apps
and you've gotten a lot of mail, loaded some big web pages
in Safari and your phone is running short on RAM,
this message might get sent to your game saying, hey,
you better calm down and give up some RAM especially
if you've been a little sloppy with your coding
and you've been allocating and allocating
and allocating objects that you just don't need.
This is your application's chance to give memory back
because if you don't cooperate and if you don't try to respond
to this programmatically, what do you think Apple does
to your program while running on the user's phone?
They just kill it.
After some number of seconds if your application has not freed
up some megabytes per Apple's request, they kill it
in the interest of a good user experience.
But if you've wondered why applications might just
disappear from the screen, could just be
that it's really crappy code and they had some memory error
and just the thing crashed and Apple just terminated it
for that reason, or it just got memory hungry.
Didn't adhere to this admonishment and so,
iOS killed it for that reason as well.
[ Inaudible Remark ]
Au contraire, so it is very easy to start allocating objects,
maybe keeping them in around an array
that you actually don't really need, or even in the context
of the upcoming project which we'll talk
about in the lab on Wednesday.
You'll have an opportunity to load tens of thousands
of English words from a dictionary file
that we will provide to you and it's very easy to keep those
around in memory in the original data format and
yet you don't really ever need it again.
And if you don't think about when you actually need data
or you don't actually decide, you know what, I might need it
but hell I'll just reload it from the file system
when I need it, you can start churning through more memory
than you actually intend.
So, it's gotten easier to deal with memory management,
thanks to that ARC feature, automatic reference counting,
we don't have to worry about freeing memory as much
but you can absolutely allocate more memory
than you have really, really need.
Yeah?
[ Inaudible Remark ]
Statue of limitations in what sense?
[ Inaudible Remark ]
Absolutely.
So, ARC will free your memory when it determines
that you don't need it any more.
But it is very, very easy for me to declare a pointer
in a certain way and tuck it away in my app delegates
and just keep it in perpetuity
and the operating system will never know if I might need it
because this reduces to something on this--
the halting problem if you're familiar from the theory class.
You don't necessarily know if
and when certain code fragments you wrote will get called
and if those code fragments might eventually touch
that object, it can't necessarily be freed.
So, you can very easily contrive scenarios
where you consume way too much memory.
And as an aside, you can simulate this.
Thankfully, you don't have to just cross your fingers
when developing iOS apps
that you'll see this problem before you ship your program.
You can go up to hardware and simulate memory warning
and you can force the simulator to send that message
to your phone so you can figure
out in advance just how well you're handling the situation.
I see another hand went up.
Yes?
[ Inaudible Remark ]
Good question.
So, whenever in doubts, let me hold option.
Let me go ahead and click on the method name
and here we have returns a newly initialized view controller
with the nib file in a specified bundle.
So, if I keep reading here if you specify nil for--
let's see, where is the nib.
So, if we read long enough we'll get
to the discussion of the bundle.
The bundle you can think of as a program's folder.
You can have nibs in different bundles
and different folders effectively which can be helpful
for things like iPad UIs versus iPhone UIs and the like.
Nil in this case just means get me the default
which is right there and can be found by its name.
Good question.
Again, how to do with localization too
if you've got an English version, Spanish version,
both of which you created with the drag and drop interface.
Yes?
[ Inaudible Remark ]
Yes because you could let--
[ Inaudible Remark ]
Actually that's a super good question.
[ Inaudible Remark ]
You can definitely do the latter, implementing a method
that does that in the parent class.
I don't think you can access the grandparent class directly.
You need to have some kind of preparation in advance
with that parent class.
Good question.
All right.
So, wonderfully interesting maybe but at the end
of the day we still made a pretty crappy application
that just does this.
But still, there is some kind of communication now
between that nib and my code and we saw that by way
of the loading of the nib.
But this is a purely unidirectional program.
When I run it, all I see is text before me.
There's no means of interaction.
So, let's start to make something more interesting,
a little more from scratch that allows me to interact
with the application itself.
So, I'm going to go ahead and close that one,
create a new project, so not a new file, a new project,
single view application.
And this is generally where I'm going to start now
because with single view application as you saw,
we get a view controller and the nib file and the header file
and we get some additional wiring in the code,
but I could absolutely have recreated
that simple little hello class program by starting
with an empty application and going to the file menu
and saying new file and gradually adding back all
of the individual files.
The headache that arises quickly
if you start doing too many things from scratch is you have
to reconfigure some of those lower level settings
that you just get for free with some of the template.
So, I would start initially with the more useful templates
and only once you get comfortable, try recreating some
of these things as we may do in lab this week from scratch
and reconstructing with someone
at Apple who's already done for us.
So, single view application, I'm going to go ahead
and call this thing Nib 1, just my first example involving a nib
that I'm going to really give some thought to.
I'm going to turn off storyboards just for now
to keep things consistent with that last story.
Click next, save it wherever
and now I have essentially the same exact application I had a
moment ago.
Sure enough, if I click on my nib on the left hand side,
I just get an empty iPhone window there.
So now let's do something a little more interesting.
On the right hand side here, there's a whole bunch
of Photoshop like options whereby you can start tinkering
with the WYSIWYG, what you see is what you get interface,
the drag and drop interface.
And this is frankly a little overwhelming at first glance
and I don't think I've clicked on 50 percent of these over time
but there's a few that I occasionally use
if you're actually using interface builder
to create your UI.
One of them is surely the objects submenu down here
where I can drag and drop things like labels.
I did that before.
So, let's start there.
Let me scroll down and let me get a text field.
I want to write an application I think that allows me to type
in my name, hit Enter or click a button on my screen
and be greeted hello David
or whatever name I happen to type in.
So, some dynamism that we just haven't had to date.
So, I could of course just do this label, hello David,
but as we saw before that is not really the point here.
Well, let's actually have a text field that the user types in,
let's see a keyboard pop up and actually interact.
So, let's delete that.
And again, I'm clicking and deleting just like you would
in Photoshop or GIMP or whatever graphics program
that you might have tried in the past.
So, give me a text field and I'm going to--
notice a few things happen.
Much like in Photoshop and other programs,
you get some suggestions as to where to put it relative
to where the glass is and how thick a human finger is.
But you can ignore that.
But I'll just do that.
I'm going to now click and expand it.
So here I am programming, all right.
And now, I have this text field.
And now, notice up top there's a whole bunch of these icons.
Frankly after several years,
I still don't remember what, what one is what.
But if you hover over them, you get little tool tips.
So, this one here is called the Identity inspector,
we'll click on that in a moment.
This one is the Attributes inspector.
This one is the Size inspector
and this one is the Connections inspector.
So, let's start with Attributes inspector.
So, that's this one here.
And notice I can do a few things.
I can change the color of this text field, the font size,
how about some placeholder text?
Just like in HTML 5, you have a placeholder attribute.
I'm going to put name here.
And now notice if I look at my GUI,
I have a great outward name.
So, that's nice, it's a nice little enhancement.
How about the background?
If I click on the gray background, notice over here
on the Attributes inspector, I can choose a different color,
so that's kind of interesting.
Let's click other, zoom out so, I can see it,
choose the little crayon things and let's change it to white.
So, now I have UI more like the one I got earlier for free
by just using the empty application
and now I need a button to submit so, where is that?
I'm going to drag and drop the button here.
That's where Apple recommends I put it.
I'm going to double click on it
like in Photoshop and click type go.
But notice I could also be a little more anal and go
over here and I could manually type that here.
I can change the style of this button.
Let's see, instead of a rounded rect button,
I could do something like an info button
but that's not what I wanted.
That's that little I icon that you see
in I think the stock application.
So, let's undo that.
Long story short, I could start tinkering
and change the aesthetics of this.
But functionally, that just will get boring quickly.
So, let me wave my hand at the remainder of the attributes
that you can tinker with but it's the kind of obvious thing,
size and weight and other things.
So, what else might I want to do here?
Let me go up to the Identity inspector which is this icon
to the left of the Attributes inspector.
And I'm not going to change anything here.
But notice that there's a hint of the relationship
between this drag and drop interface and code.
I've highlighted the text field that I dragged and dropped.
I've gone to the Identity inspector and Xcode is hinting
to me that the type of object I have effectively instantiated
or alloced by dragging and dropping is what?
It's apparently a UITextField.
So we'll see in a bit I could actually write lines of code
that alloc a UITextField and encode tell it to go
to 10 pixels from the top, 20 pixels from the left.
And I could actually do all of this programmatically.
Xcode's purpose in life is just to simplify this process
at least for newbies early on to help get you started quickly
with the more user friendly UI.
So unfortunately I've made my UI simple though it is,
but it doesn't actually do much.
Let's see what it does do.
Let me go ahead and hit the play button.
That will spawn the simulator assuming I've made no
syntax errors.
Pretty good so far, looks like I expected.
I'm going to click on name.
And notice I get the keyboard for free
because it's a text field.
Apple knows that when you get focused to it by clicking
or touching on it if they were an actual phone,
they pop up the keyboard.
I can start saying something like D-A-V-I-D.
Notice it's going to try to do autocorrect for me.
So, that's kind of a nice feature.
And now I click go and of course nothing happens, right?
'Cause what should happen?
We haven't told the program what to do.
So we have to somehow now associate that button
and that text field with actual code.
So where might we do this?
So henceforth, even though you could put code
in the AppDelegate-- and in fact let me just clean this up
and get rid of all superfluous stuff.
Even though you could put code in the AppDelegate
in the header file or the M file, you typically won't.
You'll typically immediately hand off control
from the AppDelegate to a view controller,
a rootViewController, and isolate your code there.
There are some cases where that's not going to be the case.
But for now think of a breakable rule of thumb
that you should start writing all of your code
in the view controller and not start embedding stuff
in the AppDelegate.
Partly by convention here per the MVC paradigm we just
mentioned earlier.
So what should I put where?
So, if I'm going to put almost all of my code
in the view controller class, that means it should go
in the H file and in the M file.
But currently these files look like this in the H file
and in the M file, which looks like this.
And honestly, this is really uninteresting.
I'm going to get rid of this.
I'm going to get rid of the private catego--
the semiprivate category.
I mean, this class literally does nothing.
But I need a way of somehow linking this class
with that user interface.
I need some kinds of like extension cord
that wires the nib, the UI, with my code.
And so the mechanism that Apple offers
for this is something called an IBOutlet
for Interface Builder outlet.
And you can kind of think of it as a socket
into which you can plug a cable
to somehow wire these two things together.
So the paradigm for doing that essentially boils
down to declaring properties.
So what I'm going to do in my ViewController.h file inside
of my class declaration here, I'm going to go ahead
and start typing property and I'm going to know
in advance it's going to be non-atomic, strong.
In the future we'll think harder about that.
But for now let's just go on faith and say
that it's no-atomic and strong or strong, non-atomic.
Order does not matter.
IBOutlet and then UITextField.
And let me close this window over here
to give me some more room.
Star textField semicolon.
All right, does this look like a valid declaration?
[ Inaudible Remark ]
Exactly. So, this is a bad sign.
If I click at that expected semicolon and edge
and declaration list,
it actually doesn't quite know what I'm talking about here.
Let's try to fix that.
IBOutlet, resave, problem goes away.
When in doubt, simply changing things
in Xcode doesn't necessarily mean Xcode will notice,
but generally saving the file will mean it will reanalyze your
code and get rid of any warnings or errors.
OK, so what does this mean?
Well, a property is just a means
by which we can synthesize a getter and a setter
and give us dot notation access to some instance variable.
By convention, what is the instance variable going
to be called that is behind the scenes for this property?
Any one recall or know?
This used to be more explicit but more recent versions
of iOS just kind of do this for us.
By convention, what Apple--
[ Inaudible Remark ]
What's underscore text field.
Yes. So by default what Apple does these days is
if you declare a--
if you declare a property called textField, they will create
for you a UITextField star underscore textField instance
variable for you inside of the object.
But we shouldn't have to know or care about that
because the property gives us getter
and setter access to it, but just FYI.
OK, so what is an IBOutlet?
Well, what's interesting is because I typed IBOutlet,
notice this little circle that appeared here.
Let me get rid of IBOutlet, hit save, it goes away.
Let me put it back, save, and come on, comes back.
So notice, this is kind of cute.
If I-- can I do this here?
Damn it, I need to have two windows open.
We'll come back to why that's cute.
All right.
So, how do I actually now connect,
and that represents the source of socket
that I alluded to earlier.
How do we actually connect that line of code to my nib file?
So we can do this in a couple of ways, but what I'm going
to do is first, let's say, go to my nib file over here
and I'm going to expand this window here.
And this is a little complex at first,
but now I'm in ViewController.nib
which gives me my user interface that we defined earlier.
And now notice on the left hand side,
we get this little cheat sheet of placeholders
where I have the objects in my view.
Now what does this mean?
For now notice that.
I'm going to just drag this over here so they're side by side.
This big rectangle is itself a UIView.
Where did it come from?
It just came with a template.
I got a default UIView rectangle by default.
I then started dragging and dropping stuff on there.
Case in point, I'm going to delete the go
and notice the placeholder at top left is about to disappear.
So that's where it came from.
So if I go back to my little menu on the right hand side
and I grab myself another rounded rectangular button,
drag it here, notice it reappears under view.
And that's because this is indeed something akin
to a canvas.
They gave me a blank canvas at first.
It was gray, then I made it white.
And then I started dragging and dropping different like layers
or objects on top of it,
and that's the hierarchal representation of that.
Constraints, we'll wave our hands up for now.
That just has to do with supporting devices
of different sizes like an iPhone like this,
an iPhone like this or like this, or an iPad.
But those are given to me by default just to help me out.
And now up here is something called file's owner
and first responder.
Well, ignore first responder for now.
But file's owner refers to the class
that has ownership of this nib.
So per our discussion earlier, which class owns this nib
or uses this nib to load its views?
The view controller.
So really, that icon which is
like a yellow cube is just an iconic representation
of my class, it just represents my code.
Now why is this useful?
Well, notice, if I click on control here
and then start dragging, notice that this little--
we'll call it an extension cord, starts to appear.
This blue line starts to appear and it wants to lock
on to things over here.
And I'm going to go ahead and hover over the textField
and I'm going to let go.
And now notice Xcode tells me that I have a few outlets
that I can plug this blue capable into.
One of which is called textField,
one of which is called view.
The fact that there's a little minus sign there means
something's already plugged in there, just don't touch it,
that's what came with by default when we got this whole view.
But textField looks familiar, right,
that was the name I gave to what?
That was the name I gave to the property
that I typed out in the H file.
So simply by selecting, with my mouse, textField,
I now get some kind of association, a line goes way.
But there some kind of association made
between the files owner, aka ViewController.m or .h
and that particular widget inside of my view,
it's like I've plugged one into the other.
So what does this really mean?
This means that when I run this program,
my property called textField which is of what type?
It's a pointer, which means it's meant to store an address.
So what I have just done with this drag
and drop interface is I've told Xcode, when you load my program
and when you load this big rectangle
and you start plopping the textField there
and you put the Go button there.
What-- the last thing I need you to do before you hand control
to my application is figure out, what is the address in RAM
of that textField that you dropped there
for m. What is the address of that button that you drop there
for me and put the address
of the former, the textField, where?
Inside of the property that I declared called textField
which is a 64 bit chunk of memory
in which I want the address of that textField.
So again, all interface builder is doing for us is kind
of simplifying, dumbing down if you will,
the process by which I can create a user interface
and it is going to do for me the process of allocing
that UITextField, figuring out with the return value
of alloc is after initializing it and then putting
that 64 bit memory address into my property.
And that is again what the dragging and dropping
and that blue line have done for us.
It's saved me the trouble
of doing the assignment operator somewhere in code to figure
out the address of that UI text filled.
So, what's the implication of this?
Well, the implication is we can do one other thing it's one
thing to have a connection from my code to inteface builde.
Why is that useful?
It means I can probably programmatically ask the user
interface for what?
The value, so, if the user type something in much like in jQuery
or Java Script you can ask a download what is its dot value.
Similarly now in Objective-C,
can I programmatically ask what is the value
of what the human typed
into that text field 'cause I have a connection
from my code to the text field.
But that's not quite enough to make an application
that allows me to type in my name and then see a prompt
on the screen because in order to inform the program
that I have typed a word what's the human convention to hit
like enter or hit the go button.
So, I somehow need a cable going
from that go button back to my code.
So, the opposite of an IBOutlet is what we'll call an IBAction
and I declare that in my H file as follows,
dash 'cause it's going to be an instance method, IBAction.
And now notice Xcode is trying to be helpful.
Let me do that again.
IBAction. Notice that it's encouraging me
to give the selector.
Selector is a fancy way
of saying method name colon ID sender.
So, we'll come back to ID sender in a moment.
I'm going to go ahead and call this something somewhat
arbitrary, go.
This is the method I want the UI to call
when I click that go button.
Now, ID sender, this it turns out is just a convention now.
IBActions, if you read the documentation,
state that when an IBAction a.k.a. method is called
as a result of a user doing something
with the user interface, that method called go in this case
but it could have been called anything,
is past a pointer to what do you think?
To the object that was touched on the screen.
So, it's a way of potentially having multiple buttons
for instance all invoke the same method
but I can somehow identify which one
of them was actually touched,
and maybe those buttons have different meanings
on the screen.
In this case it's [inaudible] 'cause I just have one.
But if I had multiple that would be useful.
What is an ID?
It's a data type recall.
Yeah?
[ Inaudible Remark ]
It's not necessarily a void pointer, it's a--
it is a pointer that can be nil.
So, ID is like saying void star, for those of you
who knew C or C++ before.
But it's a pointer that can also be nil.
So, this is sort of the common Objective-C way
of saying this is a pointer but it might be nil.
It might not be a valid value.
OK, so, I'm done with that.
Oh and now notice, here is where it got useful.
Because I have this circle now, notice it's filled in.
That's because I've plugged something in to the outlet
with that little blue line.
All right, so IBAction go.
All right, I'm really eager now.
I'm going to go ahead and click run here.
All right, so I'm going to see my UI in the simulator.
And notice for some reason the latest version
of the iOS simulator is slow to start but here it is now.
I'm going to go ahead, very exciting, D-A-V-I-D, go.
Why is it not working?
Yeah, I didn't link it, right?
All I did was declare a method that happened to be called go
but I made no programmatic connection between that method
and the UI, and indeed the little cute circle here is still
empty, we haven't wired those two things together.
So, let me go back to my nib file.
And actually notice, Xcode is pretty good.
Xcode underneath the hood uses a compiler called clang whose
error messages are pretty decent and pretty human friendly.
Incomplete implementation, it's slapping me on the wrist
for having done exactly what we identified
as the problem already.
So, if you get this here, notice it took my files away.
Not a problem.
See the little folder icon at top?
Click that, and I'm back where I expect to be.
Let me go to my nib file,
and now notice this time I want the arrow to--
the blue line to go in the other direction.
I want the button to be linked to my code
so that messages can be sent from button to code.
So, again, I'm going to hold control.
I'm going to click on go.
And now notice, little blue line starts to form and it wants
to cling to a few things but I know just intellectually
that this belongs tied to my class
where that IBAction was defined.
So, if I let go over files owner, notice that the events
that I can wire this into is go.
And here honestly Apple is just inconsistent.
They call it an IBAction in one place.
Here they call it a sent event.
So, the same exact thing.
So, I'm going to click go and that linkage has now been made.
Indeed, if I go back to my code, notice the little--
whoops, notice in the H file the little circle has been
filled in.
And I can confirm as much now.
If I go to the nib file and I click on--
control click on this button, notice that whole--
it turns out there's more
than just the default blue line that can happen.
Notice there's a whole bunch of events
that a little itsy bitsy button like the go button can send.
The one that's inferred to be the default
when you just start clicking with control and dragging
and creating a blue line is an event called Touch Up Inside.
That's like OnKeyUp, it's on TouchUp.
So as soon as my finger comes up,
this event is going to get fired.
But clearly there's other ones related
to dragging and other things.
But that's the one that Xcode does by default.
Suppose you didn't really know that or you wanted
to change it or you just goof.
Notice I can undo this.
Oops, that was a mistake.
But no worries, I can zoom out.
And now notice, I can go to Touch Up Inside,
the little circle becomes a plus.
And if I click there and notice, I can drag to files owner,
choose go again, so two different ways to now do this.
And we'll give you a third.
If I now delete that, so the blue line is now gone.
Now I can enter a different mode in Xcode
and the screen is a little small,
so this won't quite do it justice.
Let me hide the view over here.
And notice if you just click around, you can do no wrong,
you can just hide things
by clicking somewhat obvious buttons.
I'm going to go to this little butler icon in the middle
which is called the-- what's he called?
Assistant editor.
And if I click this, notice that I get a split screen.
Unfortunately my screen is somewhat small,
so this is somewhat underwhelming.
But if you have a nice monitor at home, this is compelling.
Notice now that it's a butler when--
a butler icon because it's the assistant
and it's trying to be helpful.
When you click that icon, Xcode will typically open
in another window the file
that it statistically thinks you are likely to care about next.
And in this case, it got it right.
I'm in my H file.
I want it to be in my nib file also because now,
notice this cute little circles finally have some applicability
because I can see them on the screen at the same time.
So if I click on control here and drag down to here--
oops, sorry, goes the other direction.
If I click on the plus there and go to my button here,
I can actually wire it to go in exactly the same way.
So many, many different ways to do this, let me go back
to the simpler code window.
I personally find it easier to just control click on the icon
and then just start dragging and dropping, let go, choose go.
Everything is now wired.
You can verify as much by clicking control,
looking that Touch Up Inside is referencing File's Owner's
go method.
And conversely, if I go to File's Owner, click control,
zoom in here, there's some stuff I didn't do.
Apple did some of this, but notice that textField is linked
up to the Text Field Name which is exactly what's in the UI.
So again, three different ways to now wire this thing together.
All right.
So now, OK, really excited now,
I've got everything wired up bidirectionally.
I'm going to click run.
It says stop Nib1.
That just means the simulator is already running.
I'm going to ignore that and just tell it
to restart the simulator with my new code.
Everything is wired up, very excited, type in D-A-V-I-D, go.
Damn it, my first crash.
So this is the debugging window down here.
Anything that looks
that unintelligible means you screwed up somewhere.
So what did I do wrong?
Yeah?
>> You didn't implement the method.
>> I didn't implement the method.
I declared to the world I am implementing a method called go
and then I never got around to implementing it.
So it's like I've referenced an invalid pointer effectively.
So, let me zoom out, where do I-- oh, my God, what the heck--
so there is your threads we promised earlier.
I'm going to go back
to the folder view 'cause I know what the problem is.
Where do I solve this problem?
[ Inaudible Remark ]
Yeah, the dot M file for my view controller.
So first, let me go to my H file.
Let me go ahead and copy the signature of this method,
just to save myself some key strokes.
Let me go to ViewController.m and notice Xcode knew
and warned me in yellow incomplete implementation,
so that's another advantage of using the H file in promising
to implement something.
You can now follow through on that.
Let me go ahead and start implementing that here.
Question?
[ Inaudible Remark ]
That is a good question.
Let us see.
Let's click on the arrow, incomplete implementation.
Let's see if we go up here, incomplete implementation,
method definition, there we go.
So short answer, yes, and I found that by clicking
on the little yield sign here, the exclamation point,
digging down through the hierarchy.
And then, Xcode reveals some more explicit information.
Yes?
[ Inaudible Remark ]
Because-- that's a good question.
It is not a-- well, so we could turn on certain levels
of warnings to tell the compiler,
"Don't let me compile this."
By default, it will assume that I know what I'm doing.
Maybe I'm linking in the implementation of that method
in one of those libraries that we saw earlier.
So maybe buried deep inside one
of these frameworks is an implementation
and I'm just making a commitment to the linker that it will--
those bits will appear eventually.
Short answer is we could change that behavior if we wanted to.
By default it doesn't protect us from ourselves.
Yes?
>> That string in hexadecimal, is that the location where--
>> Yes. This is all-- these are all hex values and presumably,
I don't know for sure here,
refer to memory addresses probably inside
of this dynamic library which is code
that Apple wrote that's been compiled elsewhere,
I'm guessing.
RJ?
[ Inaudible Remark ]
[ Laughter ]
[ Inaudible Remark ]
There we go.
So yes, it's a little part--
hard to parse visually but terminating app due
to uncaught exception
in NSInvalidArgumentException not helpful,
but this gets more helpful.
Go, unrecognized selector sent to instant such and such.
So this means exactly that.
You passed a message to an object and that message that--
that implementation was not actually there even though you
promised that it would be.
All right.
So, easy fix.
Let's go ahead and in my M file start implementing this.
And let's keep this super simple.
I just want a sanity check that I'm doing something right today.
So, I'm going to call NSLog of "here" just to prove to myself
that this code is getting called.
But this isn't quite right, so couple of things wrong here.
I haven't done something right here.
Oh, and I'm also in the wrong file.
So, all right, stupid Xcode.
So even though that's highlighted,
I'm not actually there.
Let me click on the M file and now put this where it belongs.
But there's another error.
[ Inaudible Remark ]
Yeah, where do I put an at sign.
>> In front of the first quotation mark?
>> OK, in front of the first quote mark but why?
That looks like a string already, it's quoted.
[ Inaudible Remark ]
It's not an NSString.
So an NSString is a special string object.
It's a class construct that means there's more to the string
than just a sequence of characters.
It's not a char star from the world
of C. It's an actual Objective-C object.
So NSLog, if you want more information, click on option,
click the question mark and you can read more about it.
But again, it's like printf, but it prints to a standard place
and that standard place for now is going to be down here.
This is also useful if you're programming the app
onto the phone.
You can actually connect the phone
to your computer via USB cable
and you can actually see the NSLogs
of your application running
on an actual device via the same mechanism.
Generally though, you should remove all
of these things before you ship your product otherwise anyone
can see you're debugging messages by plugging their phone
into like iTunes and watching some of these messages
or the Xcode counterpart.
OK, so what I'm promising here is
that when the go method is called, it's just going to print
to the log at the bottom of the screen here with a bunch
of exclamation points, and that will be progress.
More so-- more than we had thus far.
So let's run this with the play button down here, OK.
D-A-V-I-D, go.
Whoa! Finally, I'm programming for real.
So, it's not that interesting.
The timestamp is changing so it's happening again and again
but of course I'm not actually getting the value that's
in that text field.
So we need to go one step further.
So how can we about getting that value?
Well, let me try-- how best to do this?
Let's try this.
So, hello comma, how do I put a placeholder in for a string
that I'm going to insert later?
Yeah, so percent S--
>> Percent at--
>> Percent at sign if it's going to be an NSString,
so I would have figured that the hard way if I got it wrong
and it wouldn't-- and it would give me a little red flag.
So hello here, close quote, comma, now I need a way
of getting at my name that's been typed
in by the human programmatically.
So recall that we have in my dot H file a property called
text field.
How do I get access to that tech-- that property in code?
What do I type?
[ Inaudible Remark ]
Self, yeah, but typically self.textField
and notice Xcode knows about it, so it's going
to auto complete for me.
And then how do I get
at the value 'cause text field is an object.
I'm actually not sure so I could read the documentation
but I've read it in advance and if I start autocompleting here,
it turns out that in N-- that a UITextField object,
if you read the manual, has a property associated
with it called a called text whose data type is apparently an
NSString pointer.
So it's a string.
So I'm going to go ahead
and just do self.textField.text close paren, semicolon, save,
and all those errors went away.
So this is a very poor man's approach
to making an application that dynamically says "Hello,
David" or whoever I type in albeit to the log down here.
So let's go ahead and clear the log
by clicking this little Clear button.
Let's rerun the program at top left.
Here's the program.
I'm going to go ahead and type in D-A-V-I-D, go, all right.
So no one else besides me with a USB cable can see this
but at least I'm programmatically accessing the
name and if I change this to, let's say ROB,
notice that now we're seeing Rob's name
on the screen as well.
Question over here?
All right, but we can do better, right?
This is the horrible, horrible iOS application, so-- or PROB.
All right, so let's see how we can do better.
So let's borrow some of the same constructs we've been relying
on thus far in the language
and do something a little more interesting.
I'm going to go ahead and first let's say declare an NSString
pointer called S and I'm looking at my cheat sheet here
so that we produce now live will actually match the sample code
that you can download and play with later
so that we get this right, and I'm going to declare NSString
and it turns out you don't always have
to do alloc and init.
A lot of classes, NSString among them, have convenience methods
that do the alloc on the init for you.
And this is one such method,
stringWithFormat is a message I can send to the NSString class.
It's a class method and I can very quickly get back a string
formatted in a certain way and I'm going to do
"Hello comma percent at" and then I'm going
to dynamically plug in self.textField.text semicolon
So to recap, what's going on here?
On the left hand side of the equal sign, what is happening?
Someone? Yeah?
>> Creating a pointer.
>> Creating a pointer, 64 bits of memory,
it's going to be the address of what kind of object?
NSString. Am I instantiating an object?
So not yet, not until the other side, the right hand side.
At which point, I'm apparently calling a method called
stringWithFormat that if I read the documentation will tell me
that it's a class method that returns a pointer
to an NSString object constructed per
that format string.
So, what do I want to do with this?
Well, Xcode if I'd click on the exclamation point,
it's unused variable S. I've not done anything interesting.
So let's do something a little more sexy.
UIAlertView, and for those of you with iOS devices,
this will look familiar.
Pointer, I'm going to call it an alert.
And now, this is going to look a little messy until I tidy it up.
UIAlertView alloc, and now I'm going to initWith--
this is one hell of a method.
All right, so trivia, what's this method called?
OK, initWithTitle message delegate--
>> cancelButtonTitle.
>> -- cancelButtonTitle otherButtonTitles.
OK, so it doesn't always read like a sentence
but that is the name of the method so it's
like a method really with multiple arguments.
All right, so let's see, initWithTitle.
What do I want the title of this thing to be?
Let's say "Finally!"
What do I want the message to be?
How about S 'cause I took the time to construct S in advance.
Message delegate.
I don't want to delegate yet so I'm actually going
to change this to nil for now.
We'll come back to that and what it's doing, cancelButton string.
So cancelButton string is essentially the dismiss button.
So I'm going to go ahead and call this "Thanks!"
And otherButtonTitle, I'm going to go ahead and say nil.
And otherButtonTitle means if you want more
than just one button, this is how you give an array
of buttons two and three and four and so forth.
Semicolon, save.
OK, why is the Xcode not happy with me now?
[ Inaudible Remark ]
I haven't used it yet.
I've used S now, so I've solved one exclamation points issue.
But if I click on this,
it's going to tell me alert is not use 'cause obviously I've
not used it.
Now this is a mess.
It's hard to read.
It turns out if you start hitting Enter in your code,
what Xcode will do is rather anally line things
up with the semicolons as is the convention stylistically
in Objective-C.
So the IDE will do that for you.
And this is though strange looking,
it's a lot more readable than a line
that wraps and wraps and wraps.
So we'll leave it in this fashion.
All right, now what do I want to do?
I don't know.
I don't remember, but no problem.
I know I have a UIAlertView object.
I'm going to go ahead and click Option, get the question mark.
OK, the documentation is a little sparse here so I'm going
to click the class reference.
And now what can I do with the UIAlertView?
Well, there's the method that we described very
verbosely earlier.
It turns out there's some properties, delegate,
alertViewStyle, title, message, visible, so we've seen hints
of some of those existing.
AddButtonWithTitle, numberOfButtons--
what do you like so far?
[ Inaudible Remark ]
Show. All right, so let's see what show is defined as, show.
So, displays the receiver using animation.
All right.
This is a very complex way of saying show the alert view.
So let's try that.
This is an instance method, returns nothing, so I just have
to send a super simple message to my code.
So I'm going to go on my new line here and say--
how do I send the show message to this object?
Just alert show, all right.
All right, so let's see what now happens.
I'm going to click Run, Build Succeeded.
I'm going to go ahead and type
in D-A-V-I-D, and here we go, go.
All right, so now with some more respectable iOS out.
Finally is the title, Hello, David is the string S
that I passed in as the message.
Thanks is the default cancel buttons icon or text rather.
And if I click that and indeed it goes away.
So, I can be a little more anal here.
I'd like to make this a little sexier like when I see
that prompt, when I click go, why is the keyboard still there?
Right, like you're seeing it through the translucent button.
Let's clean this up.
And I would only know this by Googling around a little bit.
But what I'm going to do here before we actually display
that alert is I'm going
to do self.textField resignFirstResponder.
So this is instructive if only
because we've seen this buzz word responder before,
first responder, the guy to respond to like a key press.
Well, how would you say, "I'm done responding?"
How do you put something away?
Well, if I send this message resignFirstResponder status
to the text field object to which I have a pointer
in that property that I declared earlier,
I can tell the keyboard, "Go away".
Like the user gave focus to the text field,
this effectively blurs the text field.
And again, it's not as simple as focus blur,
I have to read the documentation
to know what the message is called.
But if I try this now, notice it's a little sexier.
D-A-V-I-D, go, and it goes away
because it's resigned its first responder status.
If I give focus again to the text field,
it comes back and it now goes away.
So, there's a bug though.
If I go up here and I type in PROB again and hit Enter
or even physically go down here, this feels unnatural, right?
I shouldn't be forcing the user
to hit go even though they have a return key on the keyboard.
So how do we go about capturing that?
Well, who might know if and when return is entered?
What do I want to wire to what do you think?
Yeah?
>> The text field to go.
>> Yeah. So previously we wired the go button to the go method
but we didn't wire the keyboard
or the text field rather to that same method.
But the text field should surely know when one
of its buttons is pressed.
So let's see if we can find that.
Let me go into the nib file.
Let me go ahead and control click on the text field and,
oh my goodness, so many different things,
and Did End On Exit, Editing Changed, Editing Did Begin.
Unfortunately, if you just rely on the default
by clicking control and dragging,
you don't get the right events.
But what I'm going to do here is I think the one I want is Did
End On Exit, and again completely unintuitive,
but if you read the documentation you'd see
that defined.
Let go, select go, and let's see if I remembered right.
All right, if I click run, boot this up and I'll go ahead
and type in RJ this time and enter.
Nice, RJ. Let's do it again.
RJ, no periods, click Enter, finally, and it actually worked.
All right, so how did I know this?
Well, honestly, it's really by trial and error.
Had I done it the other way first, let's control click,
let's get rid of the X there.
Let's just do the default and click and drag files owner,
choose go, on faith, good to go.
Not quite.
'Cause if I now click here,
notice that it's Editing Did End is the event that's assumed
to be the default by Interface Builder, which is not correct.
The one I used a moment ago was Did End On Exit.
Again, completely unintuitive,
and there's a slight distinction.
Editing Did End is what gets fired when you take focus away
from the text field but the catch is
that hitting Enter doesn't take--
technically take focus away.
What happens when you hit Enter is an event called Did End
On Exit.
And I mention this 'cause honestly,
the first experience you'll have hands on in lab
and with the first project,
there's all these stupid little things that are very easy
to trip over even when you have a super simple application
and I can't emphasize enough when first acclimating to this
to really just kind of retrace your steps,
go back to the sample code from lecture,
figure out what's different between your code
and say the lecture code, and you'll find
that it's just these little tips and tricks
that you'll stumble upon so that you don't make those mistakes
again the second time around.
Yes?
[ Inaudible Remark ]
OK.
[ Inaudible Remark ]
Very good question.
So let's go back to my ViewController.m.
If I had code executed right here,
would it get executed immediately?
Short answer, yes.
So, we can actually think back to our discussions of Ajax.
This is an asynchronous call
which means the message show is sent immediately
to the alert object, but the next line
of code will immediately execute.
And it turns out that
that message box may actually take a split second
to actually appear.
So if you want to actually respond to the dismissing
of that text, of that alert view,
you have to adopt something known as a delegate
and use a protocol of sorts.
We'll come back to that in just a moment
and that's again much like Ajax.
These are asynchronous operations, and we'll have
to inform the class if we want it
to tell us something in return.
Other questions?
So let's propose a cliffhanger here?
Suppose that the functionality I want to implement next is
when I type in something like D-A-V-I-D and click go,
I like the keyboard going away,
I like the message then coming up.
What I don't like now, anal as I'm feeling here,
is that when I click thanks, I don't get the keyboard back.
It still says David.
This is really kind of a sloppy application.
I'd really like focus to be given back to the text field.
I want to see the placeholder text again
and I want my cursor flashing there
for the next round of this game.
So in other words, we need now per your comment a moment ago,
we need some way of having the dismissal
of that alert view window signal to my code
to do those cleanup steps.
Give me the keyboard back, give me focus back,
delete David and start anew.
Let's go ahead and take our second five-minute break here
and we'll come back and solve that problem.
All right, I know it's late but we're almost there
and this next stuff will be amazing.
But it will make you better at this.
All right, so we are back.
So where did we just leave off?
So we have an implementation of view controller now
in both our H file and our M file
that does relatively little.
In the H file we have a property to that text field.
Notice we don't have a property to the go button.
Why don't we need a property to the go button?
[ Inaudible Remark ]
It's not an IBOutlet and we don't really need anything--
we don't need to pull anything from it.
It in a sense is going to push information
to us when it's clicked.
So we don't need a property for that.
And if I look now at my M file,
notice that all I've implemented is that IBAction
and that IBAction is called go and it just does all
that UIAlertView stuff.
But what we don't yet have is the ability to detect
when the user dismisses
that UIAlertView button labeled thanks.
As an aside, IBAction and IBOutlet, what are these things?
It turns out it's just a very clever typedef.
Typedef is a way of declaring a synonym in C, in Objective-C,
whereby you can give a new name to a data type.
And so IBAction is actually literally a synonym for void,
and void means a nonexistent return type.
It doesn't return an actual value.
So all Apple has done is they have declared that IBoutlet
and IBAction are synonyms for void.
So the effect of this is to have no functional impact
on your code.
The compiler doesn't care.
But what Xcode does is it uses regular expressions essentially,
skims your code and anywhere it sees an IBAction,
it realizes that it can put this cute little circle here
and it can put that name go into the little dropdown menu.
Same thing in the H file for the IBOutlet, this too is just--
this actually isn't void, this is quote unquote.
So literally it's a synonym for nothing.
So, if the compiler gets rid of that,
it has no functional effect but it does know
to put the little cute circle and to put the text field
in the dropdown that we saw when I was dragging
and dropping the blue line.
So it's kind of a clever hack, if you will,
to make the Interface Builder work without having
to fundamentally change the language.
All right, so let's now wire together the thanks button
with our code in a way that allows us to round off the last
of the technical topics from the very start of lecture.
So we looked at categories briefly,
let's lastly look at protocol.
I'm going to go into some of the prefabbed code from tonight
into a file called Nib2 so that we don't have
to rewrite all of that code again.
Nib2 I'll tell you upfront is almost identical
to the previous example except
that in advance I have solved this problem
of wiring the thanks the button up with my actual code.
So let's look
at ViewController.h. Do you see anything different in this file?
[ Pause ]
What's different?
Yeah.
[ Inaudible Remark ]
Exactly. So we have UIAlertViewDelegate
which wasn't there before in the previous example, Nib1.
This file was almost the same but that was absent.
So the fact that I have UIAlertViewDelegate
in angle brackets just means that my class, view controller
that descends from UIViewController is also going
to implement some methods declared in that protocol.
Now, I forget what they're called
but this is easily solved.
Let me hold down option, click on UIAlertViewDelegate,
click on the reference, bring out the documentation.
And if I read this closely, you'll notice that,
you'll notice that if you add your own button--
no, not that one.
What do I want here?
Scroll down.
This one, alertView didDismissWithButtonIndex.
That is apparently, if I read the documentation closely,
that is the method that will be called when the user did dismiss
with a button index of zero,
in the default case, that thanks button.
So I just have to implement that now to be able to detect
with an event listener that the button has been pressed.
So let me go into my M file and see how I've done this.
So what did I do here?
Interesting.
So, alertView didDismissWithButtonIndex.
What did I decide to do?
So my comment is kind of spoiling the fun here.
But when that UIAlertView sends this message
to my view controller object, I'm executing one line of code
which apparently does what?
Clears the text field.
How do I do that?
I can simply set the property called text that's associated
with my text field to nil quote unquote effectively.
Or setting it to nil is that-- because of the setter it knows
to set it effectively to quote unquote.
So that's how I clear it so that I see the placeholder text
again, not D-A-V-I-D.
And then lastly-- this actually I did not mean to leave this
in the distribution code.
This was me tinkering around before.
I will remove this.
If I leave that in there, as soon as the alert view comes up,
it goes away 'cause I was experimenting
with a different example.
All right, I'll fix that on the online source code eventually.
So, there's one other difference between this file
and the last one but it's a little subtle.
What else have I done that's different?
Yeah, excellent.
So, whereas last time the value
of delegate was nil, this time it's self.
So this is a very common paradigm in iOS whereby
when you call a method on some other object,
in this case the object
in question is this UIAlertView object, and you want to inform
that guy to whom he should send the message
when he's done doing something, you can pass
in a delegate reference, a pointer to some other object.
In this case, who do I want to be informed
when that button is clicked?
My self. And literally, I pass in therefore self.
Now this works because the UIAlertView object knows
to send the message called alertView didDismissWithIndex
to its delegate.
If it's nil, no big deal, it's going to send the message
into a black hole so no one hears that message.
But if I'm telling it that I am your delegate,
let me know when you're done being clicked on,
send me a message, I just have to pass in self.
And because I have implemented this method now, I can hear it.
If I get rid of that, the message might still be sent
to me but it's just going to go into a black hole as well.
But here I've intercepted it much
like registering an event listener with JavaScript
or jQuery in the most recent project.
Yeah.
[ Inaudible Remark ]
Who's holding a pointer to the alert when the--
so we have in this line here,
so this is where automatic reference counting comes
into play.
So, we have here an allocation of the UIAlertView object.
We have a pointer here.
We're then sending the message.
Essentially what is happening here is the operating system is
going to keep track of who still has a pointer to that object.
And because this is the only guy in existence that has a pointer
to that object, effectively when it goes
out of scope it will be reclaimed
when it's no longer in reuse.
And let me wave my hand at the memory management details
for now 'cause we'll come back to this
in particular next week especially the notion of weak
and strong as it might relate to something like this
where you're passing a pointer
from yourself to some other object.
But this is some of the magic
that now happens underneath the hood
because of that feature ARC.
Previously we would have had to free it eventually ourselves.
Technically there's an autorelease pool that does this
for us and automatically frees the memory eventually.
All right, so let's take this up one more notch.
I'm going to kind of whiz through this code just
so that we've-- you don't feel that you're entirely dependent
on this Interface Builder.
Let me open up NonIB.Xcode project.
And in this example, if I expand the files over here,
notice that we again have main.m and let me emphasize here,
when in doubt when reading someone's code
for the first time, certainly lecture examples
and even Apple's or others, then it gets helpful to start
with main.m just to reassure yourself, OK,
familiar, nothing there.
Let me now follow the breadcrumbs
and go to AppDelegate.
OK, now I'm going to AppDelegate.h. Nothing new here,
this looks like the example from awhile ago,
ViewController pointer and a window pointer.
AppDelegate.m, no, nothing interesting in here.
It looks like the brains of the operation are indeed
in the ViewController.
Let's look at the dot H. OK, little interesting here,
alertView didDismissWithButtonIndex go.
OK, that's actually the same as before.
Notice I'm being explicit as someone asked earlier
with read/write even though that's the default,
I could say read-only.
ViewController.m. So here's the difference,
and you can immediately see why I used Interface Builder
at first.
This is the code with which I've implemented things
without a nib.
Notice missing at top left is ViewController.nib,
so I'm doing it sort of the real way
like without using a little drag and drop WYSIWYG tool.
So, the price you pay is that it's a pain in the ass
and so here is the number of lines of code I've written.
And this is a bit
of an exaggeration 'cause I could have relied
on some defaults for some of the properties you're about to see.
But I included them just to make explicit what the code looks
like for a lot of those Photoshop
like attribute settings that I was so pleasantly clicking
and dragging on earlier.
So, loadView, if we read the documentation is a method
that comes with the UIViewController class
from which I descend.
And he load-- is responsible for loading the graphics
on to the screen if you're not using a nib file.
So because we have no nib, I have to do everything manually.
But it's pretty readable,
and I've certainly commented it succinctly
but hopefully clearly.
Create view.
How do you create the view, how do you create
that default rectangle on top
of which we start putting all of the other objects?
I do self.view.
I allocate a UIView and I initialize it
with the frame much like we did before.
Slightly different application frame
but it's essentially a boilerplate code
from documentation that I learned from initially.
And that just gives me that rectangle.
Self.view.backgroundColor gets white color.
That's how I make the background white.
So we've seen something like that before.
Now, it gets a little annoying.
I have to use the Core Graphics Library.
Recall that under frameworks, we had CoreGraphics.framework.
Well, it turns out all these little buttons,
even though they're kind of ovular little curvy,
I mean they're two-dimensional graphics.
And they come-- there's from lines of code like this.
I create a CGRect frame by calling CGRectMake.
So the Core Graphics Library turns out as all in C.
So now we're using C code.
This is not object oriented code per se though it's kind
of commingled as you can see in line two here
with UITextField alloc.
But let me wave my hand at some of these details
but to emphasize this.
I looked at Xcode.
I looked at Interface Builder from the previous example
and just determine by looking at the little GUI settings
that that text field was 20 pixels down,
20 pixels over, hence the 20, 20.
I also looked at the settings and it said that the size
that I created by dragging and dropping the left
and right happened to end up being 280 pixels.
So I copied that and it happened to be 31 pixels high by default.
So I really just manually
and arbitrarily came up with those values.
Now, I'm initializing the text field with the frame.
So I have to somehow tell the UITextField where it belongs
in the canvas that I'm painting with my lines of code.
The rest of these lines here, autocapitalizationType,
autocorrectionType, these are just essentially properties
that I'm setting to constants, to turn on or off capitalization
and other UI features like that, things that I would have gotten
by checking boxes earlier.
And then placeholder, notice I get "Name".
And here now, here is where I implement those blue lines.
It's a little cryptic and it's OK
if you're not wholly comfortable with this just
yet 'cause using Interface Builder is totally fine
and frankly I think it's the better way to learn initially.
Self.textField addTarget self action selector
go forControlEvents.
OK, this is a mouthful.
And this is not uncommon.
In Apple, their constants are very, very, very long
and their name is based effectively
by having common prefixes.
So what's going on here?
I am sending a message to the text field to add
to it a pointer, a reference to myself specifically telling it
to call the go method, otherwise known as the selector,
whenever what event happens?
There is that Did End On Exit events.
Recall that Interface Builder kind of dumbed it down
and simplifies it, made it look grammatically nice with spaces
and whatnot, but the constant in code that represents the Did End
On Exit event is expressed this way.
And it's just a number underneath the hood
and it's a constant that I would only know
by reading the documentation.
So, these lines of code here that wrapped under two lines,
this is the equivalent of the blue line that I drew
from my text field to my file's owner.
All right.
Add text field to view.
So, this line of code,
addSubview is taking the text field,
taking that default view that's white on the bottom
and putting one on top of the other.
That's what adding subview does.
It just adds an object on top like you're plopping things
down on a transparency.
And now, this is actually very similar to before.
The button I create by creating another rectangle,
these numbers I figured out just by looking at what the size
of my go button was in the previous example,
could have come up with any other numbers.
Notice that I instantiate a UIButton
of type UIButtonTypeRoundedRect, that's the rounded rectangle
that I so easily dragged and dropped earlier.
I set what's called the buttons frame, so what's the rectangle
in which this button is going to live.
I then set the title here for UI state-- UIControlStateNormal.
So buttons have different states.
If you touch and hold, becomes blue usually,
that's a different state.
Just the normal state is going to be that constant.
And then here is how I drew the other blue line.
When I dragged from file's owner--
sorry, when I dragged from the button to file's owner,
this is how I implemented that other blue line.
As for the rest of the code, thankfully,
this is the same as before.
This is the same as before.
Everything else is the same.
Now, there is one new feature here, these pragmas,
these preprocessor directives.
These are just kind of a fluffy feature, kind of nice.
I haven't used this before but notice there's a little set
of breadcrumbs up here that tell me where I am.
If I click on, let's see, the rightmost one here,
notice that it's kind of organized, actions,
UIAlertViewDelegate with the bold facing and whatnot.
That's coming from this.
It is purely aesthetic just to kind
of keep your methods organized if you care to do that.
It has no functional effect on your code.
Questions?
So in the upcoming project, draft a few spec is online.
You'll be implementing a program,
recall, named Evil Hangman.
Evil Hangman is much like the normal hangman except
that it's evil in the sense that it cheats.
So whereas in normal hangman, you might choose
like a six-letter word and give blank spaces for each
of those letters and the human has to guess E or A or C or D
or whatever letters and you gradually reveal those letters
as the user guesses your word piece by piece.
Evil Hangman is a little different in that, recall,
if I guess E, even if the computer was thinking
of a six-letter word that had an E, well, now he's going
to change his mind and choose any other word
from the dictionary that doesn't have any E.
So he can say, "Sorry, no E's."
If you then are kind of smart in a sort of Wheel
of Fortune sense, you go with A, another common letter.
Computer is going to figure out, "Let me find a word
in the dictionary that doesn't have E's or A's
so I can say no, no E's or A's."
So it's constantly dodging your guesses in this way.
And it turns out that if you give the user a finite number
of guesses like four chances or five
or some relatively small number, odds are they're not going
to win the game and they're going to feet like an idiot
when they realize that the six-letter word was something
so obvious but it just didn't happen
to have the letters they chose.
And that's because the computer isn't really changing its mind
try after try, it just has a large dictionary of words
and it's constantly throwing words away based on your guesses
until you effectively paint it into a corner.
So you'll be implementing this in the form
of a utility application which is one of the templates
that was provided by Xcode.
It's nice in that it's more complex than any
of these examples we've done thus far,
and we'll see others next week as well
as others in lab this week.
But the template alone that comes
with Xcode gives you this nice little effect.
If I click this UIButton that looks
like a little information sign, notice I get a two-sided UI.
And this is nice because as you'll see in the spec,
you'll be challenged to implement your user interface,
your UIViews in the front of this interface.
But then there's going to be some settings on the back,
some sliders for instance that allow you
to change the word size to make the game easier or harder,
and the number of guesses that the user has allowed.
And then when you flip it back by calling done,
you'll actually have a chance then to play that game again.
This would be a chance to play with NSArrays,
NSDictionaries potentially,
some of the building blocks we've talked about this week
and last and we'll continue talking about next week
so that ultimately, you will begin this process by filling
in some of these blanks.
And so, what I would encourage you to do between now
and Wednesday is to actually try to one, go home,
download the source code from tonight and actually tinker
with some of the examples, delete lines of codes,
see what breaks and try to understand why.
And I would also strongly encourage everyone to take
at least one or two of tonight's examples, maybe Nib1, Nib2,
and try to recreate it.
Even if you're kind of cheating by comparing your code
against mine side by side, but go through the motions
of like writing up the code,
figuring out how we wired things together 'cause odds are they'll
take you half an hour potentially 'cause you'll miss
some stupid little detail, but it's that just kind
of muscle memory that you want to build up so
that when you really want to do things that are of interest
and sort of fun in terms of this kind of game,
you won't get tripped up on some of those little nuances.
And we'll spend more time on that in lab.
We'll also do a walkthrough of sorts to get you comfortable
with the spec and we'll dive in much deeper next Monday as well.
So I'll stick around for questions but otherwise,
why don't we call it a night.
See you next week.
[ Silence ]