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.


3. Starting and understanding what's in a new Xcode project

Now that we have a solid grasp of the basic types of data that we can use, let's go ahead and start a project to put our knowledge to use. Go ahead an start Xcode (I will be using version 4.2), and select the option "Create a new Xcode project" on the left. This will take you to the new project screen that shows you all of the different templates you can start from. That is one thing that Apple has done really well with the iOS SDK is providing great templates that do a lot of the heavy lifting right from the get go.

I definitely recommend taking a minute to browse through the different project types you can create, and see what they are capable of doing. There is a pretty good chance that at some point down the road you will be using most if not all of the templates from that list. For our purposes today, we are going to select the simple Single View Application. This template sets us up with a single blank view that is ready to be built upon.

In the next screen, go ahead and name your project in the first field (I am naming my project Example, I recommend you do the same), and set that same name in the Class Prefix, and then you probably don't need to worry about the other fields at this point. You can select the device family, which I'm just going to leave as iPhone. As for the checkboxes, select the middle one only, Use Automatic Reference Counting, and hit Next. After you select a destination for your project, hit Create and you are ready to go!

The first view you are greeted with when yo make your new project is a settings page for your application. Notice that off to the left the actual project file is selected. Anytime you want to come back to this screen, select the project file in the left hand side, and you can adjust any settings you need to. Now let's look at the files that come inside of the project, that Xcode has setup for us. You can see that there are some yellow folders called Groups that have different files in them. For the most part, the only one you need to worry about is the one called Example, that is where all of our code files are going to go. Inside of the Example group you can see that there is a nested Group called Supporting Files. That is important to know because that is where you put all of your resources (like images, audio files, databases, etc) that you want to add in the app.

Ok enough with the boring Xcode explanations, lets get into some code! Go ahead and select the name of our first view controller over on the left which is called (in my case) FirstViewController.

Wait a minute, there are two files that say FirstViewController! What gives?

I'm going to explain the difference between the .h file and the .m file in my next post. Stay tuned!

2. Using variables

In my previous post, we talked about how there are four different types of variables that make up the core foundation of programming. If you close your eyes, can you recite them? Can you remember what types of data they hold? Review and practice them until you remember them exactly.

Now let's see what these variables look like in action. This is the process of declaring a new variable in Objective-C (the language you need to learn to write iOS apps):

Integer:

int variableNameInteger;

Double:

double variableNameDouble;

Boolean:

BOOL variableNameBool;

String:

NSString * variableNameString;

How does that look? Do you feel okay about that? You're probably wondering why the string type uses a * in the declaration. That is a good question that you don't need to worry about yet :)

Keep in mind that you can set the name to whatever you want, it doesn't matter at all. Now let's go through what we are doing in more detail.

When you declare a variable, you state the type of variable you want to use, and then follow that with the variable name. It is important to remember that a variable has a type, and a name, and those are two very different things.

Also note that we are using ;'s all over the place! This is a programming convention that is basically standard across most computer languages. The ; is used to say that you are done with that line of code. Even though it might seem logical to you that if you move to a new line, that that is a different line of code, the computer doesn't see it that way. You need to tell the computer that that line of code is over with a ;.

So before we can use variables, we need to declare them, or let the computer know which ones we are going to use. So looking over the code that we have up above, do any of our variables have any values? That is the third aspect of a variable, it's value. The purpose of a variable is to be a placeholder of values, right? That means that we can give variables values, and they will retain them.

Pop quiz: What are the three aspects of these basic variable types?

Think about it.

Think some more.

Do you have the answer?

Answer: Ok, a variable has a type, a name, and a value. That makes sense, right?

Lets finish this post up by assigning values to our variables:

Integer:

variableNameInteger = 650;

Double:

variableNameDouble = 345.46;

Boolean:

variableNameBool = YES;

String:

variableNameString = @"This is a string!";


What do you notice that is different about this code? Once you declare a variable, and the computer knows it's type, you don't have to reference that variables type anymore. You can just use the variable's name. So in the code snippets above, we are simply referencing the variable by it's name, and using the = operator we're giving the variable a value.

To give you a better idea of how this works, lets go with one more simple example:

Lets do some stuff with our integer variable after the above line of code that gave it the value of 650.

variableNameInteger = variableNameInteger + 100;

variableNameInteger = variableNameInteger - 4;

variableNameInteger = variableNameInteger * 3;

variableNameInteger = variableNameInteger / 2;

What is the value of variableNameInteger?

Think about it.

Think some more.

Do you have the answer?

Answer: 1119.

Basic math operations are a fundamental part of programming with variables. Variables are quite flexible and very powerful. This is a simple idea and concept, but it is crucial to understand very well before you move forward. Everything you do with programming involves variables and values so make sure you understand these concepts perfectly.

Coming up we will get into the iOS SDK XCode, and look at how we can declare and use variables in a real life situation.

1. Variables - The building blocks of (a programmers) life

Variables. You've heard of them, but what are they? The word is used in a number of different ways, and it means a lot of different things. In order to get a solid iOS foundation laid, you need to understand the importance of variables. To begin, lets talk about one of the other places you may have experience with variables: math.

Consider this simple algebraic equation:

6y - x + z = 4

What is x? Is it a number? What is it's value? The answer is that the variable x is whatever you want it to be. This is really important to understand. Programming variables are quite a bit different and more powerful than math examples, but the idea is the same. You use a letter or a word to represent or hold a value.

So how do I use variables in programming?

In programming, there are a number of different variable types. Like I mentioned before, variables are placeholders for data. The type of data that a variable holds depends on the type of variable that it is. Here is a rough overview of the 4 basic types of variables you will need for a solid foundation in iOS development:

Integers - This variable type holds simple whole numbers like 3.
Doubles - This variable type holds numbers with decimal values like 3.14
Boolean values - This variable type can be one of two different things: TRUE or FALSE.
Strings - This variable type holds a string of text characters like "text".

These four basic data types are the core building blocks of computer programming (not exclusive to iOS). It is important to understand their difference, and when you want to use one over the other.

In my next post, I will go over how to use these variables. Stay tuned!

0. Getting started

Welcome to our first post! This is an exciting time to be alive! Never before has it been so easy to reach the wallets of hundreds of millions of prospective customers around the world. Such is the landscape of the lucrative and extremely fast-growing landscape of mobile app development.

The goal of this blog is to help people that want to get into programming (particularly iOS development) that don't have any background with it. In order to get going with this material, there are a few decisions you need to make. You need to gauge how committed you are to following through with this process. It isn't exactly easy, but definitely worthwhile!

In order to begin development for the iOS platform, you need to get a Mac! Some of you PC folks out there might groan and moan about this, but trust me, Apple is doing you a favor here! Once you convert, there is no looking back!

After you get a Mac, you need to download Xcode, which is a free app from the Mac App Store. This is the program that allows you to write programs. It was also written in Xcode...kind of trippy.

After you get that far, you are ready to get going on learning how in the world you use these tools to make a product worth selling to people. Building an iOS app is just like building anything else. You have tools, and you use your brains, logic, ability, creativity, and imagination to create something that didn't exist before. It is actually a very rewarding experience.

I hope to help lay the essential foundation of what you need to know through posts on this blog. I definitely won't be able to go over everything there is to know, but I want to help you get to a point where you can find answers to problems because you know what to ask, and where to look.

Writing software is all about leveraging human made tools to talk to a computer. We are in the driver's seat, and we are the ones in control of what we want to do. The computer just listens. All of the lessons and tutorials that you will go through in this long journey are aimed at helping you better communicate with the computer what it is you want it to do.

I hope you stay with me as we go through all of these great topics, it will be the best thing you can do for yourself!