16. IBActions

We have been doing quite a bit of work in Interface Builder recently, and we are going to keep at it in this post as well. IB is an amazing tool that can make app creation a lot easier. In this post we are going to talk about IBActions, and how they are similar to IBOutlets, but very different at the same time.

Let's see if you remember what our last post was all about. We talked about IBOutlets, can you remember what they are? What they do? How to make them? How to hook them up?

We use IBOutlets to hook up graphical objects in IB to corresponding object declarations in code. So if you have an IBOutlet object in code, and you change some of it's properties, those changes will reflect in the object in your view. Pretty straight forward.

The concept of IBActions is very similar. Instead of hooking a graphical object up to an object reference in code, you are hooking up a graphical object to a method, or an action. Let's think about that for a second. Why would we want to hook up a Button to a method? Well, do we remember what methods do? Methods allow us to run specific pieces of code exactly when we mean/need to. So if we have a button on our view, and somebody touches the button, chances are we want something to happen. This is easily accomplished with the IBAction. We can hook up the IBAction to a graphical object in code (usually a button), and so every time that button is pressed, or that action is fired, the associated IBAction, or method is executed. Let's take a look at what this looks like in the header file:

As you can see the IBOutlet from the last post is still in there. IBActions are declared in the header file just beneath the @interface. You may notice that the declaration looks very similar to that of a method. This is because they are in fact very similar.

So the above code declares an IBAction for us, so what is left? We need to do something with it, right? Based on what we've talked about already, where would we do that? The .m file! Go ahead and put this in your implementation file:

As you may have noticed, the top line of our method, or our method signature, is the exact same as in the .h file. So something that is easy to do after you declare the IBAction in the header file is to copy that line and paste it right into the .m file. Then you put the brackets in and you're ready to fill out the implementation of the action.

So based on what we have learned about NSLog, what would you expect the result of this IBAction to be? We are printing a message to the console. How do you get to the console? Try Cmd-Shift-R.

So we have our IBAction declared in our .h file, and implemented in our .m file, are we done? What is missing? Well, we have an action that is ready to be used, but we haven't hooked it up to anything! The fact that we are using an IBAction, as opposed to just a regular method, means that the actual hooking up for the action will take place in Interface Builder.

In order to return to IB, go ahead and click on the ExampleViewController.xib (or whatever your file is called) file in Xcode. Similar to how we did it in the previous post, go ahead and right-click on the File's Owner button on the left, and notice what has changed. If you're building on the previous post's content, you should still see your IBOutlet hooked up, but at the bottom of the black popup we see a new area called Received Actions has shown up. Do you recognize anything in there? It's our IBAction!

By setting up the IBAction in the .h/.m file, we have the ability to hook up our action in IB. Similar to how we did it with the IBOutlet, go ahead and grab the open circle to the right and click-drag it to the button that we have on our view. You'll know you did it right when a black popup prompts you to select which type of touch event you want to respond to.

I haven't ever really found much use for all of these different options, but you are basically looking at all of the different ways that a touch can be recognized in proximity to a button. The one that we want to use (and that you'll want 99% of the time) is the third from the bottom: Touch Up Inside. This means we want to IBAction to fire if we touch inside the bounds of the button. Pretty straight forward.

With that, we're done! Go ahead and fire up your app and see what we have done. If you want to observe the effects of our IBAction, open up the console and you can see that for every time you press the button, a message is printed in the console.

This might seem like a simple concept, or result, but the concept behind it will be used very often. We just went through and hooked up a graphical object to our code, and are able to respond to events that happen.

Because just printing to the console is kind of boring, I want to spice it up. For our next post, we are going to review many of the different operations we can do within the scope of a method/action implementation.

15. IBOutlets

When you hear the word outlet, what do you think of? There are a few different ways that the word can be used, but the one I'd like to talk about is an electrical outlet. Our homes are filled with them, and we use them all the time. The idea is quite simple; a big company does a lot of work to transport the electricity to your home and outlets, and all you have to do is plug your appliance into the outlet and you can begin using it.

Interface Builder operates in a similar manner. IB uses outlets to plug in graphical objects to their corresponding place in code. An IB outlet, or IBOutlet as they are formerly called, function a little bit differently because it isn't exactly a one-size-fits-all solution like our outlets are at home. In code, you setup an outlet for lets say a Button, and then in IB, you make the button, and then you can plug it into the IBOutlet that you made in code. Once your button is plugged into the proper outlet, you can begin to handle the events that happen on the button, like a click for example. It's that easy!

Let's dig into some code and take a look at how we need to setup an IBOutlet for our Label, Button, etc, to plug into. IBOutlets need to be declared in the .h file, so that is where we are going to add the following code:

Your .h file may have more code in it than the picture above. You can leave it there, or make it look just like what I have. Can you see what we are doing with the one line of code that we are declaring here? It should look somewhat familiar. We are in the header file and we are declaring a class variable. This isn't just any type of variable though, it is a class variable that is also an IBOutlet. Adding in that IBOutlet keyword is all we need to do to create the outlet in code that will allow us to plug in the Label in IB. Pretty easy!

Now that we have created this IBOutlet in code, lets go hook it up in IB. If you followed the last step of the last post, your view should have a Label and a Button on it all ready to go. The process of hooking the Label in to the IBOutlet we just created is really easy. Go ahead and right click on the File's Owner thing off to the left, and you should see the name of the Label variable we just made. In my case it is called greetingLabel. If you look to the right of where the variable name is listed, you should see a circle that is hollowed out. Click within the circle that is next to the right variable, and drag to the Label on the view we already have setup. It should highlight blue signifying that it recognizes that the outlet that you are hooking up to the Label is an outlet made for Labels. Let go of the mouse, and you have officially hooked up your first IBOutlet! Way cool!

One other point that I need to stress is the meaning of File's Owner. We made the IBOutlet in code in the .h file, and then it became available/visible in the File's Owner portion of IB. Do you notice any correlation? The File's Owner area can be thought of as a graphical representation of any and all IB objects that are available for hooking into.

Now you may be wondering why that is as cool as I am trying to make it sound. We just connected a graphical, movable, editable IB element to the code portion of our app. We need to go ahead and make the following changes in our .m file to better grasp the point of setting up IBOutlets:

This line of code that we are adding to the viewDidLoad method of our viewController is pretty straight forward. We are accessing the text attribute of the UILabel object that is named greetingLabel, and setting it's value as "IBOutlets are really cool". So if you go ahead and build and run the app, instead of displaying the text that you were displaying in the .xib file, it should now show the text we just set in this viewDidLoad method.

Do you see what we are doing here? We are making these variables, hooking them up to IB, and then we have access to them in code if we need it. Let me remind you that the main point of IB is to have the ability set everything up graphically the way you want it to look. It isn't always the case that you can do everything in IB because sometimes your content is dynamic in nature. This is where IBOutlets come in handy.

In our next post we are going to go over another aspect of IB called IBActions. Fun stuff!

14. Interface builder and those strange looking .xib files

How are you feeling so far on this material? We haven't really gone over very much by way of mind bending material, but it can be a lot to take in at first. I'd like to move on now and talk about the .xib files you can see on the left side in Xcode. You have probably noticed that the names of any .xib files you see also correspond with the names of existing .h and .m files. If you can recall, I mentioned that the .h, and the .m files together make up a class. This might be a little confusing, but some classes are designed to be viewed on your screen, or in other words they have a visual component to them, and then some do not. The .xib file is the designated place for setting up the visual objects for the view of a particular class.

The concept behind using .xib files to handle the visual objects of your view is that it is easier to lay things out graphically then it is to do it in code. I completely agree with this. There are those that don't prefer the graphical method, but I am definitely one that is ready and willing to take advantage of all of the tools at my disposal. Interface Builder (the built-in program that allows you to do all the cool graphical editing stuff we're going to dive into) is a very powerful tool that we are going to take advantage of. It is very important to understand that Interface Builder is a tool that let's you connect graphical objects that you can easily interact with, to your code. That's the whole point. Setting up things graphically, and then linking them into the code so that they actually do things. This will make more sense as we go along.

If you have been following along with my previous posts, we have been playing around with a simple view-based application with a single blank view controller as the main view. If you go ahead and click on the only .xib file that there is on the left (in my case it's called ExampleViewController.xib), Xcode will load the file in Interface Builder. In previous versions of Xcode, Interface Builder, or IB as I will refer to it, was a separate program that ran along side Xcode. Ever since Xcode version 4.0+, IB has been integrated into Xcode, which is great.

You'll notice that a number of different things have just popped up. You are probably thinking, "I can't handle any more stuff!". Don't worry, you can. The image below will help make sense of all of the tools that IB provides:

Similar to how we've been doing, I'm just going to go through and talk about the points I have labeled:

A - Files owner is one of the more confusing components of IB, but it doesn't need to be. I mentioned earlier that the purpose of IB is to connect graphical objects to code so that they do things. A button doesn't do anybody any good unless it is hooked up to some code that does something, right? Files owner (right clicking on file'w owner more specifically) allows you to see in IB all of the objects from the .h file that are available to you in that particular class. This will all make sense as we go along, but make sure you understand that File's owner is basically a graphical representation of the .h file (which is where you declare all of your class variables! Right?).

B - This pane is a simple graphical representation of your view's hierarchy. This can be quite a useful tool, especially when you are nesting different view's inside of each other. Based on what you see going on in the middle of the screen, with all the buttons and stuff, what can you deduce from this pane? The container view is called View, and then (because of the fact that it is indented) we know that the Button, Label, etc, are objects that are nested in that View. We put those things in the view, and this pane represents that very well.

C - As mentioned before, this list of items are the things that are actually on the container view. So you might say this is a list of subviews.

D - The graphical representation of the view itself. IB does a great job of laying out a nice canvas to begin adding all the objects you need for your view. Just so you aren't confused, I went ahead and added a number of UI objects to illustrate how easy it is to set things up in the .xib file.

E - This row of icons is actually quite important when it comes to changing the attributes of different objects in IB. For our basic purposes, we won't need to change to a lot of them, but as we go along, know that that row is the Batman utility belt of IB.

F - In this sub-toolbar, it is important to remember that you are selecting that cube that is third from the left. This gives you access to the UI element library that you can pull things from.

G - To a large extent, this is where all the magic comes from. If you scroll through this pane, you'll see a large number of things that you can add to the view that we are building. Some of these you have seen in your use with an iOS device, others you haven't. Apple has done a great job of making it very easy to add and implement all of these tools. As we move along, you will become more familiar with this area.

Before we wrap up our little intro of IB and.xib files, let's get ready to so some nifty stuff with IB. Your view should be blank still (unlike mine), and so now I want you to add two things to your view. Where do you get items to add to the view? If you look up at the image, the item library is identified in F & G. Let's go ahead and grab a Label and drag it onto your view. You will notice that if you want to center it, IB will tell you where you need to line it up. Change the text of the Label by double-clicking on it, and change it to whatever you like.

Now go ahead and grab a Button fro the library and drag it beneath your Label. You can add some text to your button in the same way you did the Label. After you save the file, run your project and see what you've done!

Okay so adding a button to the screen that doesn't do anything isn't exactly a monumental achievement, but we are making progress! In our next post we are going to go over how to hook up the graphical side of things (in the .xib file) to the code side of things (in the .h/.m files).

13. The objects in object-oriented programming

Have you heard of the term object-oriented programming before? This is what we're doing. We haven't done much with objects yet, but Objective-C is an object-oriented language, and it is something that we are going to get into a lot more going forward.

What do you think of when you hear the word object? Kind of a vague, general word, right? The idea is that objects can be anything. This is what we want for our programming purposes. We make and use objects that can be anything. We use these objects to fulfill whatever needs or purposes we have. To better understand the importance of objects in programming, lets dive in a little deeper.

Look around you right now and grab the nearest object. Hold it in your hand and look at it. What are some ways that you could describe the object to someone that is blind, and never seen it before? In my case, the object I'm using is my blanket on my bed. I might start describing this blanket as being red, and big, and having golden swirly designs on it. The blanket is pretty thick, and does a great job of keeping me warm.

I just did an adequate job of describing what the blanket is. Now if you think harder about our description of this object, what else could we say about it? The computer only knows what you tell it to know, so it is very important we understand the process of making objects. We just talked about what the object is, but what can be said about what the object has? The blanket has a texture, it has a color, it has a width, a height, and a thickness. The blanket also has a name, a manufacturer, a thread count, and even a tag on it somewhere describing the washing instructions.

Can you tell the difference between what an object is, and what an object has? This distinction is extremely important to understand very clearly. In object-oriented programming, objects are comprised of three important components:

1) The type

2) The property

3) The values

This makes sense. If we were comparing two objects that both had the same width, height, color, and shape, does it necessarily mean that they are the same type of object? Not necessarily. One object could be of type pan, and the other could be of type paper. The type is used to generally classify the object into groups.

The properties of an object describe what an object has. That shouldn't be too hard to grasp. Examples of properties are the shape, color, weight, size, etc. of an object. If it helps, think back to science class when you studied the properties of different minerals and rocks and things.

The final component of an object are the values. Properties and values are very closely related. The value is kind of the answer to the question that is raised by the existence of the property. The sheer existence of the height property doesn't necessarily mean that you know what the height ob that object is, right? It merely means that the object has a height. The value of the height property is where you understand what the object's height actually is.

So to quickly recap, object are comprised of three things. Without looking above, can you name them? Ok, an object is made of a type, properties, and values.

You may be wondering what in the world this object stuff has to do with actual programming, and the answer to that is that it has everything to do with programming. Let's think back to the very beginning, when I introduced you to variables. What are some basic types of variables? Integers, doubles, and booleans. Those three primitive (basic) data types are not objects. They don't have properties, they only have values. But if you'll remember, we also talked about another type of variable, the NSString.

Do you remember that? The NSString data type is an object because it has all three ingredients for what makes up an object. A type, properties, and values. That might sound confusing, but there is a lot more information about the NSString object that is available to us besides it's text value. We can ask the NSString object how long it is, or how much memory it uses, or what it's memory address is. Objects become really powerful (especially ones you make yourself) because you can put in and pull out as much information as you could possibly want or need.

So now that we have a better idea of how objects work, let's do a quick intro to what types of objects there are in iOS. Can you think of any besides NSString? Try and think about things that you see on your iPhone/iPad when you are using it. Anything that you see an object? Answer: everything is an object! The buttons that you press are objects. They have sizes, shapes, colors, positions, and things that they are supposed to do when pressed. Labels are objects, they have properties that you can set and adjust and change to fit your needs. Textviews, tableViews, scrollViews, webViews, mapViews, sliders, steppers, navigation bars, toolbars, activity indicators, alertViews, and even tabBars are all objects! Basically everything we do in iOS development (and many other computer programming languages for that matter) is object-oriented.

We could go on and on and on about how to make custom objects, and how to use them, and where to put them, and so on. I don't want to overwhelm you at this point, but I want to make it very clear that objects are very powerful, and that from here on out that will be a word you see more often than 'the'.

As we progress through different phases of development, we will get to understand objects a lot better. But for now, we are going to take advantage of all the amazing work that Apple has done and use the objects that they have made available for our use.

12. Our final post on method calls...for a while

This final post on basic method calls is going to revolve around calling methods with return types. Do you remember what those are? The return type of a method specifies what data type the result of your method call is going to be. We have just finished up using a number of methods that have a void return type, or that don't return anything. We are now going to examine the use of methods with basic data return types. Let's start by changing the methods in our .h file to look like this:

As you can see, I have changed up the methods that we are going to run quite a bit. Besides the method names, what else is different? How do you know what a method's return type is? The area in the parentheses at the beginning of the method signature is where you can specify what a method's return type is.

Just to mix things up, I decided to use a whole bunch of different methods and return types to accomplish a pretty simple task. It's ok though because these exercises are for learning principles, not accomplishing awesome tasks yet.

Now let's take a look at our implementation file and see what we are going to do with our methods we have declared:

Let's take a look at what we are doing:

A - So the whole purpose of all of this code is to print a simple message out to the console. If you recall back to the post on the NSLog, we use placeholders to tell the compiler to insert variable values at certain places in the NSLog message. Well, in the event that there are multiple placeholders, how does it know which one to put where? It goes by the order of appearance. So the placeholders above show up in this order: %@, %@, %d, %d, %f. It is now up to us to make sure that the variables following the end of the string message are in the same order: string, string, integer, integer, and double.

B - You recall from earlier posts the fact that often times when we make method calls to a method that has a return type, we can immediately assign the result of that call right into a variable. So it is as if the call in and of itself is actually a variable of the type that it is returning, does that make sense? If you look at the variable part of the NSLog above, you notice that there aren't any variables! That might seems confusing, but as I mentioned, we can treat method calls with a return type the same as if they were a variable of that return type. This allows us to make these method calls, and have their returning values get thrown into the NSLog message without any problem.

C - Here we are executing a simple return statement with a literal number value. This isn't always a good idea, but I am doing it here to show that it is possible to throw a raw number, or string value into the return statement.

D - Here we are declaring a local variable, giving it a value, and then returning the variable instead of the actual value. There is no real difference between these two approaches, the latter is better for humans to read because the name of the local variable lets us get a better idea of the purpose of the number. Whereas if we were to just use a literal number value, we might get confused as to what the number is for.

Can you guess what the output of our NSLog message is going to be to the console? If you run it, you should see the following message in your console:


This is one of the many ways you can make method calls that have return types. It is important to realize that you can either assign the method's return value into a new variable, or else (if it makes sense to) just treat the method call itself like a variable.

I hope you have gotten a taste of how useful and important methods are in programming. We use them all day long, so it is imperative that you are very comfortable with the previous few posts. If you are still having some issues with what is going on, go back through with the debugger and follow along with what is going on!

We're ready to move on now to some different material that will help us do more interesting things with our apps.

Stay tuned!

11. More method calls!

Ok, I really don't want to beat the dead horse here, but I actually really do. We need to make sure we really get the concept of what we're doing when we're making these method calls. So if you have been following along with me, we have a .h and .m file that have a bunch of methods, most of which are empty. We are going to fill them in now and see if can make sense of some serious multi-method calling.

This post is going to be unique in that I'm going to suggest you spend more time looking at my code and try to see what is going on with it. It is going to be a bit of a numbers game and I'd like to see if you can follow along!

Please consider the following code, and be ready to tell me what the ending value of our globalDouble variable is at the end of the program execution! Here it is:


Ok, sorry about the images being a bit skewed, but hopefully it worked out ok. Were you able to follow what we were doing? Where did we start? viewDidLoad is where we began. Then where did we go? Well, we went all over the place. Were you able to come up with an answer to the ending value of our globalDouble variable? Ok, here is the answer I got: 1344.8. Is that what you got? Feel free to put the code in and run the app with some breakpoints if you want to make sure that you understand what is going on better.

I wanted to illustrate a very important concept with this exercise, and that is that when you call into a method, you won't leave the method until any/all other method calls are completed. It gets tricky when those methods make method calls that make method calls, etc. You can quickly get lost in a series of nested method calls, so it is important to understand that is the way it works.

Ok, I hope that you are becoming more familiar with the structure of calling and writing these basic methods. I am going to do one more post on handling methods with return types, and then we will move on to more awesome material.

Stay tuned for my next post!

10.5 NSLog

In our previous post, we talked about how one of the main ways that we can access variable values is through debugging, and printing a variable's description in the console. There is another approach that is useful to know about, and it is called NSLog.

Unlike using the debugger, the real benefit of using NSLog is that you can print variable values to the console as the program executes. Let's take a look at a very simple example of how we use NSLog:


If you have been following along in my recent posts, you'll need to make sure that you are not in debug mode. Let's take a look at what we are doing, and try and make some sense of it. Our first log message is pretty straight forward. We are simply outputting a basic text message to the console. This could be useful to let us know where we are at in the sequence of code.

The next message is a little bit more complicated. We are outputting a basic message, but what is the deal with the %@ stuff? This is called a placeholder. A placeholder is used to represent a value that is on the way. So the compiler looks at the %@ sign and says 'Ok, I need to look for a string after the text message part of this NSLog is through'. Sure enough, if you look at where the text message ends, there is a , and then a variable. When the NSLog is actually executed, the compiler takes that variable's value and stuffs it into the text message exactly where the %@ was located. That's why it is called a placeholder.

The third and final NSLog is the same, but because we went off to another method and changed the variable value, the NSLog message is different.

The final point we need to discuss is the fact that there are multiple different placeholders for different types of variables. We used %@ because the NSString type is technically an object. There are lots of other types of objects (don't worry, we'll talk about them soon), and if you want to print them out in the NSLog, you need to use the %@ placeholder. Here are a few more placeholder's that you might find useful:

For printing out an integer: %d - (d? Don't ask me!)

For printing out a float/double (same thing) - %f

For printing out a boolean (technically they are just numbers, right? 1 or 0?) - %d

This is just a small sample of the different types of placeholders that you can use, for a more comprehensive list, you can Google around and find a nice list in no time, or look here.

NOTE: If you use the wrong placeholder for a variable when trying to print it's value, you will crash your app, and you will get a very vague and confusing error that will leave you scratching your head for hours. Make sure you are sure that you are using the correct placeholder!

To recap, NSLog is a very useful for printing variable values at run-time, or when the app is actually running. You will want to be careful not to use this tool too often, otherwise your console will become flooded with a large number of messages that it may be difficult to sort through.

Now, onto more about methods!


10. Method calling and debugging to see exactly what is going on

Ok, we have finally made it to our method calling debug series. This is going to be a treat. We just talked in depth about methods. Let's do a quick recap on what we learned. Do you recall what the purpose of a method is? What are the main two parts to a method signature?

We use methods in programming to go execute a block of code in another location that has a specific purpose. The two parts to a simple method as we described were the return type, that specifies the type of variable that is coming back from a method call (if any), and then the method name, which you use to actually call the method.

Let's dig into some method calling. Go ahead and make sure that your header file looks like this: (also, in case you are being offended that I am using images for my code snippets, I am doing it for two reasons: 1) It will most likely be the same as what you will see when you type it up on your screen (as far as the color scheme goes), and 2) When it comes to trying to familiarize yourself with conventions and best practices, there really is no substitute for typing out the code yourself)

And then now we are going to go ahead and provide implementations for our methods in the implementation file of our class, or .m file:

Do you remember what these { }'s are doing? They are defining the scope of these methods. We dont have anything inside of any of these methods right now, but make sure that your code has these methods included (note, there are more methods that should be in the class, I am just showing the ones we are going to be working with right now).

So before we get going we need to figure out a starting point. We have all of these methods that we would like to call, where can we stat making method calls? One of the prime places for achieving this purpose is in the viewDidLoad method. Remember that that is of the of first places that gets run after our view is presented on the screen, so it makes for a great starting point.

To begin, I would like to make a method call to our first method, thisIsJustATestMethod. Do you remember how to make a method call? What the syntax is? Think really hard. Ok, this is how we do it. We put down a [ to begin the operation, then we indicate what we are calling the method in. What are we calling it in? We are calling it on the ExampleViewController class, and since we are already in that class, we use self. So after we have [self then what do we do? We tell self what method we would like it to call and then close the brackets. Our method call is going to look like this:

So if we build and run our project, what happens? Nothing. That is to be expected, right? We haven't really setup any of our methods to do anything, other than to make a call. Let's go ahead add some code into our viewDidLoad and thisIsJustATestMethod to make things more interesting:

You see that we are making use of our globalString class variable as well as a new variable called tempString. How do class variables differ from local variables again? You can access class variables from everywhere in the class, whereas local variables are only accessible within the scope they are declared in.

So if we go ahead an run this bad boy, does anything happen? Nope. We are doing some things, but we aren't doing anything that would print anything out anywhere, or show us what is going on. I would now like to introduce one of the means that we can go in and make sure that the program is running the way we are anticipating. We are going to put some breakpoints in our app.

You will notice that in Xcode, between the file manager on the left, and the code editor in the center, there is a really thin white line area (not the really really thin one, just the pretty thin one). Try clicking around in there, do you see any blue arrows showing up? These are breakpoints! And they are your best friend. Breakpoints tell the compiler to stop and hand control back over to the user when it encounters a breakpoint. This allows us to get a really good idea of what is going on in our code. Let's go ahead and put in a few breakpoints:

Ok so I hope this is making sense. Before we run our program, we are simply telling Xcode that we don't want it to run through our code at a million mph, but we want it to stop at these certain points. We will tell it to continue step by step as we feel like it. So if you hit Run, this is the screen that you will see:

Whoa! There is quite a lot of information here, so just like before, I'll go through and explain it point by point.

A - This little toggle switch lets you know that debug mode is ON. If you deselect this option, you will notice that even though your breakpoints are still there, they turn gray, the inactive color. If you want to, you can start your app not in debug mode and enter in half way through, and you breakpoints will become active. This is just a convenient way for Xcode to let you know what you are doing.

B - Pretty straightforward, but these are your breakpoints. The blue color indicates that they are active, and that you are in debug mode.

C - This line, highlighted by green, indicates that this is the line your computer is at in the process of reading your code. You told it to stop when it gets there, and it has obediently listened to you. It is important to note that this line of code has NOT been executed yet.

D - We will talk about this more in later posts, but this window in the debug panel is called the console. This is where you can print different values and observe the behavior of your program as it runs. If that doesn't make sense, it will in a later post.

E - This window is called the Variables View. It is a quick and easy way to see the values of variables you have declared in your app as you are debugging it.

These next three buttons are an extremely important part of the debugging process.

F - This button is called the Step Into button. If you have a breakpoint on a line of code that makes a method call, you can choose this button to explicitly follow that call into the method it is calling, or else you can just choose to step over it and assume that there aren't any problems in that area.

G - The Step Over arrow is the button that you will use all of the time in debugging. Remember that when debugging, we are essentially telling our computer to drop out of warp speed, and talk to us at our level. This button is the way that we tell the computer to move onto the next line of code, one line at a time. So we stop at one breakpoint, and we want to start executing the code that follows after slowly to see what is going on, and where a potential problem might be. We use the Step Over button to do this one line at a time.

H - The Continue Program Execution button or Play button does just what you might think. It kicks the computer into warp drive again and the compier is off to the races again. The computer resumes reading your code as you have outlined it UNTIL it reaches another breakpoint (if you are still in debug mode).

Ok, with that explanation out of the way, do you feel like you have a pretty good handle on the tools we are dealing with? If you are with me still, you should be looking at an Xcode screen that is in debug mode, and that has an active breakpoint highlighted by the fact that control is waiting to read our first breakpoint's line of code. You with me?

Go ahead and hover the variable on the left side of the = sign, the globalString variable, do you see a yellow info label show up? What do you notice? It tells us that the variable type is NSString, that's fine. It tells us the name of our variable, that's cool. What about the next part? What does this 0x0 mean? Xcode is telling us that this variable doesn't have any information in it! It is blank and empty. But wait, aren't we assigning it a value on this line of code? Remember that when a line of code is highlighted by the debugger, it hasn't been run yet. That is important to remember!

Let's go ahead and execute this current line of code, and move ont the next line. How do we do that again? There is a button at the bottom that we need to use. Which one is it? We just want to move one line at a time, so go ahead and select the Step Over button.

Now that we have successfully executed our first line of code, let's g ahead and hover over our globalString variable again and see what changed. Instead of 0x0, we have something quite different don't we. Xcode is now telling us the location in memory that this variable is now living. That's pretty cool! Our tiny variable has it's own spot in memory to call home. So if we want to see the value of our variable, hover over the variable, and put your mouse pointer right over the name of the variable in the yellow square. You'll notice that it changes to a purple-ish color, and something new appeared on the left side of the box. Two little arrows pointing up and down show up when you hover inside of the info box. Go ahead and click on those arrows, and look at your first option: Print Description. This really useful feature does just what you might think, it prints the description (and value) of this variable to the console. To the what? The console. Remember that window at the bottom right of your screen? Scroll all the way to the bottom and you should see a new message that gives us the details we need about the value of our globalString variable in bold:

Is that the value yo got? It should be! This is one of the more useful ways of getting different variable values when debugging.

Now that we have moved onto our next line of code, we are in a bit of a dilemma. What are we doing on this line of code? We are calling a method, right? Well, we probably should go inside of the method to see what is going on there, so which button are we going to press in our debug panel? Step Over? Step Into? The answer is that both work in this case. I mentioned that Step Into is specifically for going into the method that we are calling. That is true, except if there are breakpoints in that method (like there is in this case), using the Step Over button will stop on the breakpoints in the method anyway. So go ahead and hit either of the buttons and let's make the jump into a new method!

The first line that we stop on is making a new local variable declaration. Step Over this line, and let's take a close look at what is happening in the second line in the method. If you hover over the tempString variable in the second line, what do you see? It actually gives you value right in the info box: This is thisIsJustATestMethod. What about if we hover over the globalString variable, does it still have it's value (you'll need to Print Description to see it in the console)? It sure does. So we make a new temporary variable, and we are going to write over the value that is already in our globalString variable. Hit Step Over and let's look at what happens.

If you print the description of the globalString variable now what do you get? This is thisIsJustATestMethod. That's pretty straight forward. Now that we are at the end of our method here, where are we going to go if we press step over? Think about it for a second. We have reached the end of the scope of this method that we called from viewDidLoad, where are we going to go now? Back to viewDidLoad! Go ahead and press the button and see how it works. We just ran through all of that code in the thisIsJustATestMethod method, and we only moved one line in viewDidLoad. Do you see how that works? I am going to belabor this point over and over so you will have ample opportunity to grasp what is going on.

Now that we are done with this basic method calling exercise, go ahead and deselect the debug mode (the breakpoints button at the top) and then press the play button.

This was the first of a few posts I want to make on method calling. I want to make sure that the concept behind it is crystal clear.

Stay tuned for my next post!



9. A little bit more (okay it's actually quite a bit more) on methods: their structure and how to call them

If you have been following along with my posts, we just went over what global variables are, and how to use them. We put them inside our viewDidLoad method, and assigned some values to show that we didn't need to declare anything, and that was all fine and everything, but what is the point? The answer is that without moving onto a different method, or scope, there isn't a point to class variables, otherwise we could just use local variables, right?

In this post we are going to talk in detail about basic method structure, and then we are going to go ahead and make several calls to clarify and cement how methods and control work together to run your program. First, let's start out with the basic structure of a simple method declaration:


What can you infer about the above line of code? Is it doing anything? Not really. Where do you think this declaration would belong? If you said the header file you are right. The above line of code is simply declaring a method. So before we dive into what the parts of a method declaration mean, I want to make sure we understand better how methods are used. So here is an example that will hopefully clarify things a little.

Lets imagine that you are the manager of a small business. You make and sell...cookies (cookies? yep :). You are sitting in your office doing things that managers do, and you are working on a to-do list you have made for yourself. These are the two things you need to do:

1. You need to tell your secretary to give you a list of your appointments for the day.
2. You need to tell your secretary to forward all calls to your answering machine.

Ok in case you are wondering what in the world I am talking about here, stay with me, it will all make sense shortly.

Lets start helping our manager with his to-do list. His first task is to get a list of appointments from his secretary. How is he most likely to achieve this? Well, odds are he is going to call her on the phone and make the request. So what will the result of his request, or call be? A list of appointments, right? That is what he hopes to achieve by making the call.

So lets move from our fictional story for a little bit and apply this same request to how we would do it in code. The manager is in one place (we'll say in the viewDidLoad method in code terms), and he needs to get something done. So the manager makes a call to his secretary and makes the request, or calls the appropriate method. We will go ahead and name this method getReportFromSecretary. We need to keep in mind when we are writing methods that it is best to keep the purpose of a method concise and direct. The purpose of this method is to get the report and then return it to the person who called it. Does that make sense?

I think now is a good time to dissect the way that we declare basic methods so we can better understand their purpose. Let's look again at what our method declaration looks like:


This basic method declaration can be broken up into two basic parts: the return type, and the method name. When put together, these two parts make up what is called the method signature. The code snippet right above is a perfect example of the method signature. Get used to that terminology because I will use it often. In the header file, and in the implementation file, a method is declared and implemented using the method signature.

We mentioned before that the purpose of a method is to run a specified block of code that achieves a specific purpose. So the idea behind calling this getReportFromSecretary method in code is that some code inside of that method would take care of getting that report for us, and then return the report back to us.

Can you conceptualize that easy enough? You call a method to run a specific block of code that achieves a task that you have designed it to do, and if applicable, it returns something back to you. This is very important. In the example above, we are saying that this particular method has a return type of NSString *. That means that I'm saying the report we are expecting back will be an NSString. Can you think of any other return type possibilities? All of the basic data types we have already talked about work great as return types for methods. Can you remember what they are? Integers, doubles, and booleans are data types you could also use as return types. So lets go ahead and flesh out a very basic implementation of the method we have declared above:


The main point I am trying to illustrate isn't how we would go about getting a report generated, so I haven't included any code about that type of operation, but I am illustrating the basic idea behind a simple method. Once the above method is called, control enters the scope of the method and begins to execute the code you have written. In this case it would be to put some kind of a report into an NSString variable. The last line of executable code, is very important. This is called the return statement. This line of code is what actually returns the variable to whoever called it. It doesn't need to be at the end, but it often is. So you might be wondering about what happens with the variable once it is returned, where does it go? To answer that we need to examine how we go about calling methods.

Before we put our method call into context, lets examine how we call methods in a generic sense. Here is the syntax:


Thats it! That one line of code is how you call a method. So what is the self business all about? Self is basically referring to the fact that you are calling a method in the class that you are currently in, the ExampleViewController. It is important to specify that because you can call methods on different classes as well. We'll save that talk for another day. So by saying self, we are basically saying that we are going to reference a method that we have declared already up in our header file. Think about that for a second, does that make sense? Self simply refers to the class you are in, it is a whole lot easier to write out that the long name of the class ;)

The next part of making a method call is to send a message to self (ExampleViewController) telling it which method to call. It knows which method to call depending on what name you send it in the message. In our case, we are sending self a message to execute the getReportFromSecretary method. The syntax for this operation is really important, so let's go over it again. Inside of two square brackets, you have a class on the left, and the message on the right. It is as if you are feeding the class on the left the message on the right. It digests your message, and does what you tell it to. You will see that pattern over and over and over again, so be sure you are comfortable and familiar with what is happening.

Now that we have discussed the basic approach to calling methods, lets put it into context. If you remember, we said our doctor has been hanging out in the viewDidLoad method, so that is where the call for the report is going to originate from. How does this look:



Does that seem right? You remember that our method has a return type of NSString, what is happening with our NSString? Are we doing anything with it? Nope. The above implementation isn't really going to work for us. We need to be sure that we are respecting the fact that the result of this method call is an NSString. We need to do something with the value being passed back. Any ideas? Lets assign it to a local variable (it could also be a class variable)!

That looks much better! Can you see what is happening? We are declaring a local variable (how do we know it is local? Because the actual data type declaration is taking place inside the scope of the viewDidLoad method, not up in the header file where the class variables go), and setting it's value to the result of the getReportFromSecretary method call! How cool is that?! The above line of code is very important to digest properly, so make sure you are completely clear on what is happening.

We can now cross the first item off on our to-do list and move on to the next one! The next item that our manager needs to take care of is telling his secretary to forward all of his calls to his voicemail for a while. Not thinking about any code, what would he do in real life? Call his secretary on the telephone, let her know what he wants her to do, hang up, and he's done, right? Lets see if we can represent this process in code.

For this next method, we can go ahead and give it a name of forwardAllMessages. Thats a descriptive enough title. You need to remember that it is always a good idea to make your method names as descriptive as possible so that when you or someone else comes to use the method, they can quickly get an idea of what the method's purpose is. We have the first part of our method figured out (the name), what about the second part, what else do we need? A return type! Lets think about this scenario for a second, what is the manager expecting to get back? A report verifying that she has done what you asked her to? Probably not. In all reality, he probably isn't expecting anything (tangible) back. So if we aren't expecting anything back as a result of a method call, how do we represent that in the method signature? The answer is void. That should look familiar. In many of the methods that we have seen already, the return type is void, meaning that there isn't a variable or value that you need to pass anywhere after you're done with executing the method.

So assuming that our manager is still being represented within the viewDidLoad method, and remembering to keep the code from our first task, lets go ahead and tackle our second task in code. Here is the implementation of our forwardAllMessages method:


How do you feel about that? Do you see why we don't need a return statement in this method? Our return type is void, meaning that the caller of this method shouldn't expect anything back. Lets take a look at how we would make the method call in viewDidLoad:


That's it! Because there is nothing coming back, we don't need to do any local variable declarations or anything. We simply are making the method call that will handle the code necessary to forwarding all of your messages. And just like that we are finished with our to-do list.

Methods are an essential part of of computer programming. You need to make sure that you understand very clearly their purpose. Methods are used to delegate routine actions to areas of code that are designed to handle them. To make sure that these concepts are crystal clear, I want to go ahead and build on this example in the test app that we are building, and start making and tracking method calls.

8. Control: Just like reading a book

As you may have noticed, programming is filled with all these words that you thought meant something different! What comes to mind when you think of control? Maybe a few different things. In programming, the word control refers to the place that the computer is currently at in your code.

Let's step back and think about what we are doing. When we write code, we make it visually appealing, and nice to look so it is easy to read. Easy to read for who? The computer? No. The only thing the computer needs is for the ; and { to be in the right place and it doesn't care what it looks like. It could all be mashed up into one line and it would run just fine. We make the code look nice so we can make sense of it. It is important to understand how the computer reads through and processes your code.

I like to think of it like reading a book. We spend our time writing this book, and then when we want the program to run, we hand the text over to the compiler, and it mashes it all together for the computer to process, and it just goes through and reads it. Pretty straight forward. But how does it go about reading it? Does it read it left to right, top to bottom? Is it right to left bottom to top? Well the answer to that is that the computer reads and process code in the order you tell it to. So you can think of computer programming as handing the computer a choose your own adventure book, and it going through to different places in the book based on where that page takes it, not necessarily sequentially. Think about that long and hard. It is like we are writing our own choose your own adventure book where our book isn't read sequentially, but depending on where we tell it to go.

So the whole idea behind computer programming is that you understand where the control is in your program, and then you send it off to do whatever you need it to do. For our basic purposes, control can only do one thing at a time. It goes where you send it and does what you want it to do. You control where the control goes, and that is how you make software work.

So how long does it take for the computer to read through our program? In the example we have been working with, it is processed extremely fast. Like fractions of a second. So in order to better understand how control works, there has to be a way to slow the computer down so we can see what it is doing, right? Right. It is called debugging. We can put breakpoints in our code that tells the ultra-fast computer to slow down and wait for us lesser humans.

We will go over that in an upcoming post, but first, more on methods ! Stay tuned!

7. Scope 2/2, class variables, and the .h file

In the first part of this 2 part series on scope we talked about the scope of methods and how to declare local variables. Do you remember what a local variable is? Can you explain it to your neighbor? It is important that you understand the distinction between a local variable, and a class variable, which is what we are going to talk about now.

You remember that local variables are only accessible inside of the scope they are declared in, right? You can't access local variables that were declared in another method. This makes sense. But as we talked about before, there are definitely times that we need to have access to variables throughout the entire class, no matter what method we are in, this is precisely what a class variable does.

In order to understand how class variables work, we need to finally take a look at the ExampleViewController.h file. Look at the image below to understand the main parts of the ExampleViewController.h file, or the header file:


Ok, so you're probably noticing that your header file does not look like the image above. I realized after looking at the header file that it was very empty, so I went ahead and filled in a few things to give us something to work with. As before, I'll go through and talk about each part I have identified in the image above:

A - Similar to the implementation file, the header file also has a place for importing files. This is necessary for when you are referencing other files or classes and the compiler needs to know where to look for information about what you need.

B - This part of the interface declaration specifies what type of class you are working with. Note that whatever is to the right of the : in the interface declaration is the class type. In this case, our ExampleViewController class is of type UIViewController. That probably doesn't mean a lot yet, but it will later on.

C - This is where you are giving a name to your interface, or class. Note that this field should be the same name as the name of your .h and .m files.

D - This arrow is actually pointing to all of the variable references. It is within the interface declaration that we can declare our class variables, or variables that we can access from all over the class, no matter what method we are in. Notice that the convention is the exact same, we are just declaring variables inside of the header file. The header file will take care of the task of letting the implementation file know that there are some class variables, or global variables as they are commonly referred to, that are available for use.

E - This last arrow is also pointing to this group of method declarations. Just like variables, we need to declare the methods that we are planning on using in our implementation file. This area of the header file is where you make these method declarations.

That wraps up our overview of the basic structure of the header file. Now lets see these class variables in action! If you have declared the variables in the header file like I have done above (for now you don't need to worry about declaring any of the methods in the header file except for the first one thisIsJustATestMethod), you should be ready to start using them in our implementation file.

Lets go ahead and make some basic variable assignments in our viewDidLoad method with our newly declared class variables. How might you go about using a class variable? Do you need to declare anything? Nope. Take a look at the image below:

That's pretty easy, right? We don't need to declare anything or anything! We just reference the class variable by name, Xcode recognizes it as a class variable, turns it green conveniently, and you are ready to use it! Let me reiterate the fact that the thing that makes class variables really useful is that you can reference them anywhere in the class. As we go along, the importance of that statement will continue to sink in. But in order for us to move onto how we can set our class variables in different places in the class, there are a few more things we need to cover.

Stay tuned for our next post! Don't bail on me!

6. Scope 1/2

Scope is another term that is used in programming that has a lot of meanings in a lot of different places. The concept is very important for everything we are doing moving forward so we need to make sure there aren't any questions about what scope is.

When we talk about scope, we are often times talking about the scope of a method. So for convenience sake, let's go ahead and look over the image we were working with in the last post:

We talked before about how C1, C2, and C3 are all methods. Methods are used to execute a specified bit of code, and only that bit of code. Does that make sense? When we talk about the scope of a method, we talk about the space that will be executed when that method gets called.

The scope of a method is defined by a pair of matching { } braces. Look up at the picture above, can you see how that makes sense? With C2 for example, we have a method called viewDidLoad (which gets called when the view finishes loading everything up), and then all of the code that resides within the scope or matching { } braces will get executed. Because you are going in and out of so many different methods throughout the life cycle of your app, it is very important to understand the scope, or the boundaries of each method.

To further understand the importance of scope lets get in and write some actual code like we did back at the very beginning of this journey when we talked about declaring variables.

Inside the scope of the viewDidLoad method, lets go ahead and declare some variables. We want to make an integer named integer1 with a value of 10, a double named d1 with a value of 45.6, and a string named text with a value of iPhone.

Pop quiz! Can you remember enough about how to declare variables to make those declarations inside of the viewDidLoad method?

Give it a whirl!

Ok, time is up, this is what it should look like:


Even though we didn't go over this initially, it is important to see that you can declare variables with values. So you don't need to declare them, and then set values afterward (even though you can do that), you can just set it all up in one line.

Let's start thinking about what we have now. This method viewDidLoad is one that gets called by the system every time the view finishes loading. In other words, we have a convenient place to do some stuff whenever our view finishes loading. Do you understand the scope of the viewDidLoad method? What lines of code are going to be executed when that method gets called?

Answer: All of them! Every line of code that is within the opening and closing { } or curly braces will be run. Make sure that makes sense because it is very important.

Another very important aspect of scope is that it acts like a sandbox between different methods in your implementation file. To illustrate what that means, consider the following two methods:

Look closely at what is going on, can you see what the problem is? Think about it. Think some more. Any ideas? Ok we have a new method here that I descriptively named thisIsJustATestMethod. Inside of the scope of that method we are declaring three new variables and giving them different names than in the first method. That's perfectly fine and dandy. But what about the values we are assigning to these new variables, why is there a red line underneath them? We declared them and assigned them values up above in the viewDidLoad method didn't we?

The problem here is that the definitions of the variables that we are referencing in this new thisIsJustATestMethod is out of the scope! It doesn't have any idea what those variables mean or what their values are because they were declared out of the method's scope. These variables are referred to as local variables. Local to the limited scope of the method. Do you see what I mean? Let's see if you can think of something you could do to make it so that we aren't getting errors in the second method. Any ideas?

How about this:

As it is with so many things, in programming there are a lot of different ways to solve the same problem. We don't really need to declare those variables inside of viewDidLoad, right? We could just move them down so that whenever the second method gets called, that code gets executed. Do you see any red lines? Any errors? Nope. That is because our scope issue is gone. We are referencing variables that are declared in the same scope and life is good.

So you might be wondering, there has to be a way to access variables outside of the scope of a small method, right? You are right. In my next post we will talk about how to get access to variables at a class level, known as class variables. Stay tuned!



5.5 Comments

Ok so this won't take very long, so it only gets half a number, but I think it is important to go over the concept of how to comment out code. If you look at the picture from the previous example, you may be wondering what all of that green text is for. That text is commented out. That means that to the compiler, it is as if it isn't even there. This becomes really useful when you want to start making comments about different things you are doing in code so that when you come back, your intentions are more transparent.

You may not realize this yet, but there will come times when you go back and look at some code that you wrote and you won't have a clue what is going on. Comments are an important and essential way of making code easy to read and understand.

There are two ways that you comment out code:

// Text - Two forward slashes indicate that you want to comment out just one line of code. Putting these two slashes at the beginning, or middle of a line will comment out and make green all the code to the right of this declaration.

/* Text */ - This notation allows you to comment out multiple lines of code without having to do a bunch of slashes. It is like the shortcut for mass-commenting out.

To better internalize these concepts, look over the image below:


5. The .m file structure, and a tiny bit about methods

If you're following along with me from the last post, we just ventured a look at the ExampleViewController.m file. Understanding the basic structure of the implementation file is critical for everything we do going on. Let's look at an image that shows us the main parts of our implementation file:

Just to make things simple, I'll go ahead and point out some relevant points about each letter:

A - This area of the implementation file is where you import files. This is how you connect the .m file to the .h file, you are actually importing it at the top telling the computer that there will be things referenced in the .m file that are actually defined or detailed in the .h file. As the complexity of our app increases, you will see the need to import other class header files as well.

B - This line points out that everything below is the implementation of the ExampleViewController class. The syntax is pretty self explanatory. You won't need to do anything with this other than know that that is what it is doing. It might be helpful to scroll all the way down to the bottom and see the @end symbol. That is telling you where the implementation part of the ExampleViewController class ends.

C - As you can see, there is more than one C that we are looking at. The reason for this is that these pieces of code are the same thing. Look those pieces of code over, can you see any similarities? You are looking at three different methods. A what? A method. Say it out loud five times. Similar to variables, methods are an essential building block of programming in Objective-C.

Aside from import and a few different declarations you may do at the top of the .m file, basically all of your .m file is going to be methods. It is important to note that for the most part, all the code that you write has to take place inside of a method.

In my next post I will discuss the importance of scope within a method.

4. Understanding the difference between the .h file and the .m file.

So if you are still with me, you are in Xcode looking at the left side of the screen, wanting to click on the ExampleViewController, but you notice there are two files with that same name! What I am about to discuss is very important to understand, so read carefully! The two files of the ExampleViewController have different and unique roles. When considered together, both of those files constitute what is known as a Class. That's right a class. A gathering of students to hear a lecture type of class? No.

Whatever concept you have in your mind of the word class, throw it out the window right now. I am not going to describe in detail in this post how we use classes, but you need to start getting used to the terminology. When I talk about the ExampleViewController class, I am referring to the ExampleViewController.h and ExampleViewController.m files. Together they make up the ExampleViewController class. Pound that term into your head because it isn't going to go away.

So you might be wondering, what is the difference between the .h and the .m file?

Well, the things that you do in the two files are different but complimentary. The .h file refers to the fact that it is the header file, where certain things about the class (as a whole) are declared and detailed. The .m file implies that it is where the implementation of the class takes place, or in other words, it is where you do things with the variables you have declared in the .h or header file for the class.

It won't be beneficial to discuss much more detail at this point but it is important to note that these two files work together. As we move along, we will keep coming back to the purposes of the two files and you will see very clearly how they work together.

To start off our coding expedition though, we are going to jump straight to the implementation file. Which one is that? The ExampleViewController.m file.

Stay tuned for the next step in the process of building a firm iOS Foundation.