2011年10月27日星期四

iOS For High School Students: Getting Started

iOS For High School Students: Getting Started:

The Essentials


You want to learn to develop iPhone apps, eh? Well learning to program is the first step. Before we jump straight in make sure you have a Mac (preferably one that is not super old) and Xcode.



These are the bare essentials. I recommend that you also invest in the book, Programming in Objective-C by Stephen G. Kochan. I honestly believe the best way to grasp programming is to jump in and the conceptual understanding will follow.

Click Setting Up Your Programming Environment

for a visual guide into setting up Xcode, otherwise follow the instructions below :).

Create a new Xcode project! For the template go to:

Mac OS X>Application>Command Line Tool

Title your project: Are You A WIZARD? Change the file type to: Foundation. On the left side of the window is just a simple file hierarchy. The file main.m is really the only thing we are going to work on, and it’s already highlighted :D. You should see the following code:



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// insert code here…

NSLog(@”Hello, World!”);

[pool drain];

return 0;

}


Well you’ve done it! You have created your first application! Excellent job!:p

Understanding The Hello World Application


Press run in the upper left hand corner. By clicking run you are actually telling Xcode to build (compile all the files into a single program) and to run the program. You should see the following output in the lower part of the screen:

Hello, World!

After I explain each line in the application above, we will get straight to the “Are You A WIZARD?” game.

This section of the code below is just some information, it is completely ignored when it is compiled. It’s just useful to know if you decide to share your code. When the compiler reads every line of the program and translates it to a language the computer can understand (1′s and 0′s), the “//” tells the compiler to ignore everything else on that line. It’s also how programmers can document their work by writing comments into the code that do not affect the program. We will use some in a little bit.



// main.m

// Are You A WIZARD?

//



This statement simply means “go grab the Foundation/Foundation.h it has some stuff that we need in the program we are about to write”. We could import any file. However, the Foundation.h (foundation.header file) is the one we need for our command line application.



#import


This next line is the most fundamental line. When you program, you will have to import various files that you create, define methods, blah blah blah. However, after all of the stuff you create and import is brought together, the main {} is where you begin to execute each step. This is a super lame analogy bare with me :/. If you were to bake a cake, you would gather all the contents you need with all the tools you need first right?. For example, you might get the eggs out along with the milk, pan, egg beater, etc. Well the recipe is where you get the instructions for all the different materials and tools. The ingredients and tools are like the header file in a program, and the recipe is like the main function in a program. I hope that helps. The main function is not just a line, it’s everything within main’s brackets.



int main (int argc, const char * argv[])

{
}


*The brackets {} and everything in between are called a block statement. Every statement within a block statement requires a “;” at the end.

This next line allows our program to use (borrow) memory from the computer for our application. Don’t worry if it is still confusing, all will be cleared up in the future :).



NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];



This next line is just a comment. We discussed earlier that anything listed after the “//” is just a comment; it’s completely ignored by the compiler.



// insert code here…



NSLog is our first function. In essence, it just displays everything between the first and second double quotation marks. NSLog displays a string (a list of characters). The statement Hello, World! is just a string of various characters (H-e-l-l-o-,-W-o-r-l-d-!).



NSLog(@”Hello, World!”);


After NSLog, our program has served its purpose. However, we have borrowed memory in an autorelease pool, and everything that required memory is now finished. Although the applications we write will not be memory intensive on a mac. It’s important to establish good memory conservation habits, because the iOS devices have very limited ram. Every time we borrow memory from the device and forget to release it, that memory cannot be used for other important tasks. So, the line below drains the “pool” of memory so the device can use the memory elsewhere.



[pool drain];


Finally, the last piece of code! “Return 0″ terminates the main function by requiring the console to return the value 0, if everything was successful. Go ahead and click run again on your program. The final line of output should read “Program ended with exit code: 0″. If you get code: 0 then everything ran correctly. Go ahead and substitute the value 3 for 0 in your main function (return 3;), and click run. You should understand that the output basically spits out whatever you want to test that it ran correctly.



return 0;



Phew! Hopefully this doesn’t look too intimidating anymore. The first step to working through a new programming language is getting the Hello World application running (a program that prints: Hello, World!). Xcode has the Hello World code built into its templates, which is why all you had to do was press run, but NEXT! we begin creating your own application involving wizards and special powers!



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// insert code here…

NSLog(@”Hello, World!”);

[pool drain];

return 0;

}



Creating Our Own Application


Now we are going to begin constructing the Are You A WIZARD? program. The goal of the program is to tell you what you are, based on your input. So the program will ask questions that can be answered on a scale of 1-10. We will create the questions and responses that the computer will spit out based on our input! This is a text-based program, and there is a lot of potential to make fun programs for your friends to try out! Let’s begin.

First, we don’t need the NSLog statement or the comment above it, so both are removed.



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

[pool drain];

return 0;

}


Variables


We need to create some variables. Variables are incredibly important because it becomes significantly easier to manipulate information with variables. Let me demonstrate. If we wanted a program that would multiply any number by 10, divide it by 3, and then subtract 15, we could do this:

((3 * 10)/3)-15; for the number 3

((5 * 10)/3)-15; for the number 5

((22 * 10)/3)-15; for the number 22

Each time we would have to write out the equation for each input: 3, 5, 22. However, we could write the following equation:

((x * 10)/3)-15; for any number x

This becomes really convenient in the future! Anyways, we need some variables. There are different types of variables, and we need to tell our “brainless” computer what type each variable is :p.

int: stands for an integer variable; a whole number, a number that is not a fraction; examples: -2,-1,0,1,2

float: stands for a floating-point variable; any number that is expressed with a decimal; examples: 3.5, 3.0, -.001

double: stands for an extended floating-point variable; any number that exceeds the range of float; examples: 10000000000000000

char: stands for any character variable; examples: x, a, b, d, $, #

We create variables by making the following declaration:

int x //this basically means we created an integer variable named “x”

float bee //this is a float variable named “bee”

It’s not enough to just create a variable though we have to assign it a value right? In the following examples, there is a difference in memory between saying that x equals 3 and x is assigned the value 3. A little later we will evaluate the symbol for equals.

int x = 3 //reads we have an integer variable named x that is assigned the value 3

float bee = 3.434 //reads we have a float variable named bee that is assigned the value 3.434

In our program, we have to create some variables. You can create your own if you want. However, I strongly recommend working through this tutorial copying my variables, so that you don’t run into any errors!! Change em later friends :).

I added the following variables in the main function below: strength, intelligence, speed, alchemy_skill, sum, avg.



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses (they are all float variables)

float strength, intelligence, speed, alchemy_skill, sum, avg;

[pool drain];

return 0;

}


*Some of these might seem confusing or unnecessary but we will explore the need for each one!

*Notice how I commented my code. It just makes reading the code a little easier to understand :).

I declared my variables as following:

float strength, intelligence, speed, alchemy_skill, sum, avg;

However, you could also write them like so:



float strength;

float intelligence;

float speed;

float alchemy_skill;

float sum;

float avg;


Although they haven’t been assigned a value yet, they will be shortly.

Printing Statements


Let’s create the questions we want the computer to ask.

What is your strength?

What is your intelligence?

What is your speed?

What is your alchemy skill level?

Now we want our computer to print these statements. Each of these statements is just a bunch of characters crammed together right? So, we use the NSLog function which prints a string (recall a string is just characters strung together). The format for printing a string is as follows:

NSLog (@”What ever you want to say :p.”);

DUH! Easy right? Well the questions would look like the following in our program.



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses.

float strength, intelligence, speed, alchemy_skill, sum, avg;

//I included (1-10) so that people would know how to answer

NSLog (@”What is your strength (1-10)?”);

NSLog (@”What is your intelligence (1-10)?”);

NSLog (@”What is your speed (1-10)?”);

NSLog (@”What is your alchemy skill level (1-10)?”);

[pool drain];

return 0;

}



Go ahead and run the program to see what we got so far! That’s it, you’re done! Just kidding, let’s keep working :).

Using Scanf For Input and Assigning Variables


The next big thing is that we want the user to be able to interact with the program. Fortunately we have a function specifically that takes input from the keyboard, scanf(). The function scanf() takes an argument you input and it stores it as a variable that you created. Below is an example of the scanf() function. I will paraphrase exactly what it is telling the computer.

scanf (“%f”, &strength);

Wait for the user to input something(this is the argument), the argument must be a float because of “%f”, store that input as the variable “strength”.

Realize that %f and & are just part of the syntax you will need to memorize. Because we are storing the input in a float variable “strength”, we use %f. If our input was being stored in an integer variable we would use %i instead. Below are the various operators used with their respective variable types.

int %i

float %f

double %f (it happens to be the same as float, since it is just an extended float)

character %c

Since we want to get input from every question, we just need the scanf() function after each question! Give it a try and check your program with mine below.



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses.

float strength, intelligence, speed, alchemy_skill, sum, avg;

//I included (1-10) so that people would know how to answer

NSLog (@”What is your strength (1-10)?”);

scanf (“%f”, &strength);

NSLog (@”What is your intelligence (1-10)?”);

scanf (“%f”, &intelligence);

NSLog (@”What is your speed (1-10)?”);

scanf (“%f”, &speed);

NSLog (@”What is your alchemy skill level (1-10)?”);

scanf (“%f”, &alchemy_skill);

[pool drain];

return 0;

}


This program so far tells the computer the user’s strength, intelligence, speed, and alchemy skill. Basically, those variables get assigned a value according to input. However, we have some variables that were not assigned a value.

float sum

float avg

We have to assign the values of sum and avg, after strength, intelligence, speed, and alchemy_skill have been assigned. Let me define sum and avg first, then I will clarify why the order is important.

sum = strength + intelligence + speed + alchemy_skill

avg = (strength + intelligence + speed + alchemy_skill)/4

Because sum is stored as the value of (strength + intelligence + speed + alchemy_skill strength), intelligence, speed, and alchemy_skill must be assigned a value first. Similarly avg is stored as (strength + intelligence + speed + alchemy_skill)/4 so intelligence, speed, and alchemy_skill must be assigned a value first. After placing the declarations for sum and avg after the last scanf () function your program should look like as follows:



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses.

float strength, intelligence, speed, alchemy_skill, sum, avg;

//I included (1-10) so that people would know how to answer

NSLog (@”What is your strength (1-10)?”);

scanf (“%f”, &strength);

NSLog (@”What is your intelligence (1-10)?”);

scanf (“%f”, &intelligence);

NSLog (@”What is your speed (1-10)?”);

scanf (“%f”, &speed);

NSLog (@”What is your alchemy skill level (1-10)?”);

scanf (“%f”, &alchemy_skill);

sum = strength + intelligence + speed + alchemy_skill

avg = (strength + intelligence + speed + alchemy_skill)/4

[pool drain];

return 0;

}


Programming with Logic: If Statements


The next step, requires the computer to print a message based on the skill set of the user. This requires us to write some logic code. For example:

If speed is really high and intelligence is really high then print the message, “you are an assassin”.

If strength is really high then print the message, “you are a troll”.

Here are more quantitative specifications and commands. Following this example is code to communicate these ideas to the computer.

If strength is greater than or equal to 7 and intelligence is greater than or equal to 7 and the average of the combined user’s alchemy skill and speed is less than 7,

then print: You are a clever brute. You are known for your defense of aristotle’s logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.

Below is the code that executes what I stated above. See if it makes sense, it’s something new, but you should be able to make some connections :).



if (strength >= 7 && intelligence >= 7 && (alchemy_skill + speed)/2 = greater than

>= = greater than or equal to

< = less than

= 7 && intelligence >= 7 && (alchemy_skill + speed)/2 = 7 && intelligence >= 7 && (alchemy_skill + strength)/2 = 7 && intelligence >= 7 && (strength + speed)/2 = 8 && avg = 5 && avg = 0 && avg < 5) {
NSLog(@"You are a peasant. Your lord is cruel. He does not compensate you for the work that you accomplish. You only dream of being successful :(.");

}


We are going to take these if statements and paste them into our program after the declaration of the float avg.



// main.m

// Are You A WIZARD?

//

#import
int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses.

float strength, intelligence, speed, alchemy_skill, sum, avg;

//I included (1-10) so that people would know how to answer

NSLog (@”What is your strength (1-10)?”);

scanf (“%f”, &strength);

NSLog (@”What is your intelligence (1-10)?”);

scanf (“%f”, &intelligence);

NSLog (@”What is your speed (1-10)?”);

scanf (“%f”, &speed);

NSLog (@”What is your alchemy skill level (1-10)?”);

scanf (“%f”, &alchemy_skill);

sum = strength + intelligence + speed + alchemy_skill;

avg = (strength + intelligence + speed + alchemy_skill)/4;

//These are the different logical statements so that we get a response based on our input for the various skills!

if (strength >= 7 && intelligence >= 7 && (alchemy_skill + speed)/2 = 7 && intelligence >= 7 && (alchemy_skill + strength)/2 = 7 && intelligence >= 7 && (strength + speed)/2 = 8 && avg = 5 && avg = 0 && avg < 5) {

NSLog(@"You are a peasant. Your lord is cruel. He does not compensate you for the work that you accomplish. You only dream of being successful :(.");

}

[pool drain];

return 0;

}


Solving Problematic Inputs with While Loops and Else Statements


Well, the program is pretty cool, but there’s a few setbacks preventing it from the being a killer program. Run the program a few times, each time use one of the below sets of input:

1.) 12, 14, 56, 2

2.) 8, 8, 4, 4

3.) 10, 10, 10, 10

Let’s discuss the following problematic inputs:

12,14,56,2



Although in the print statements we declared that answers ought to range from (1-10), the reality is that the user can input whatever they want. If they do put answers outside of the range (1-10), the program ceases to function :O.



As the rage comic indicates, we need a while loop to overcome those inclined to rebellious behavior. The idea behind the while loop is this:

While people answer values we don’t want, tell them their stupid, and make them answer the question again. (:p just kidding).

While strength is greater than 10 or strength is less than 1, then print: Your answer is deceitful! What is your strength? Next, use scanf () for them to retry their input. This should make sense when you read the code below.



while (strength>10||strength<1) {

NSLog (@"Your answer is deceitful!");

NSLog (@"What is your strength (1-10)?");

scanf ("%f", &strength);

}


You might be asking what is the difference between a while statement (often called a while loop) and an if statement.



if (strength>10||strength<1) {

NSLog (@"Your answer is deceitful!");

NSLog (@"What is your strength (1-10)?");

scanf ("%f", &strength);

}


An if statement runs once. After the completion of its conditions: strength>10 or strength<1 it runs its statements and concludes.

If we entered the following input into the if statement:

1.) 57

2.) 64

We get the following output. Notice that the if statement ends and stores 64 as a legitimate value of strength :(.



We simply need to add a while loop for every variable that needs an input of value 1-10. Write out the while loops, then check your code with what is below. Run the program and test entering input outside of the range of (1-10). The while loop prevents the user from advancing until conditions are met.



// main.m

// Are You A WIZARD?

//
#import

int main (int argc, const char * argv[])

{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

//These are the different variables that will be evaluated to generate responses.

float strength, intelligence, speed, alchemy_skill, sum, avg;

NSLog (@”What is your strength (1-10)?”);

scanf (“%f”, &strength);

//Each while statement is designed to make sure that inputs for each question are between 1 and 10

while (strength>10||strength10||intelligence10||speed10||alchemy_skill<1) {

NSLog (@"Your answer is deceitful!");

NSLog (@"What is your alchemy skill level (1-10)?");

scanf ("%f", &alchemy_skill);

}


Our program is significantly more sound because of the while loops.



Alright, let’s move on to the next problematic output (We are almost to the coolest part of the program!):

8,8,4,4



For a single set of input we get two outputs :(. This means that some of the conditions for our if statements are conflicting. Basically, the input: 8, 8, 4, 4 means the user is a clever brute :p. However, it just so happens that also the average of 8,8,4,4 generates the response: You are a commoner. The input 8,8,4,4 is only one example, there are several other inputs that also generate two responses. We don’t have to test every possible input with each if statement. We just have to use something called an else statement. Let me explain how they work in simple terms.

if (trees are green)

then (teach kids that trees are green)

else (teach kids that trees have something covering them)

We can also use an else if statement; A clever brute could make sense of the code below, can you 0.o? :)

if (trees are green)

then (teach kids that trees are green)

else if (trees are white)

then (teach teach kids that trees have snow on them)

When I designed the program, knowing that sometimes two answers would be generated, I just used a bunch of else if statements. Use the image below to understand how else if statements and else statements work.



In the series of if statements in the picture, the arguments only go out the horizontal tubes if they pass the condition. Once they pass the condition they are no longer considered. Immediately after the first statement, x is no longer considered. Else statements and else if statements can only follow after an if statement. At the beginning of every new if statement all variables are considered again.

Forgive any redundancies, if, else, and else if statements are incredibly important. All you have to do now is look at your if statements. Keep the first one as an if statement and make each of the ones following an else if statement. Look below for reference. All you are doing is creating the vertical tube illustrated in the picture :).



if (strength >= 7 && intelligence >= 7 && (alchemy_skill + speed)/2 < 7) {

NSLog(@"You are a clever brute. You are known for your defense of aristotle's logic, while being equally admired by competent athletes. In the gladiator ring, your intelligence outmatches beings of even greater strength.");

}

else if (speed >= 7 && intelligence >= 7 && (alchemy_skill + strength)/2 < 7) {

NSLog(@"You are an assassin. Your sharp blade and agile mind, gleam in the shadows. Being not particularly confrontational, you wear an aura of mystery.");

}

else if (alchemy_skill >= 7 && intelligence >= 7 && (strength + speed)/2 = 8 && avg = 5 && avg < 8) {

NSLog(@"You are a commoner. You will live a long life, and tend to your property.");

}

else if (avg >= 0 && avg < 5) {

NSLog(@"You are a peasant. Your lord is cruel. He does not compensate you for the work that you accomplish. You only dream of being successful :(.");

}


When you input (8, 8, 4, 4) you only get one output :D.



The Infinite While Loop


The final and most important part to the “Are You A WIZARD?” program is about to be revealed. Up until now there has been no reference of any wizards, so we must create an output for a user who possesses the greatest traits. Right now an input of 10, 10, 10, 10 results in the following output (or lack thereof):



In order to change this, we are going to create an infinite loop (for fun)! This is where we use the integer sum. Remember the operator rules that == means equal to. The only time that the sum of all four skills can equal 40 is if they are each 10. Paste this on the line before your first if statement. Make sure you understand what this is saying.



while (sum == 40) {

NSLog(@”You are a WIZARD!You cannot be defeated!! this simple program, loops in honor of you!”);

}



A while statement will execute the command until the condition is no longer met. This statement reads while the sum equals 40, print the NSLog statement. Run the program, see if you qualify as a wizard :p.



Hopefully this tutorial was helpful in your pursuit of programming!

没有评论:

发表评论