Learn to Code iOS Apps 1: Welcome to Programming

Learn to code iOS apps using Apple’s development tools. For complete beginners – no prior programming experience needed! By Mike Jaoudi.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 5 of this article. Click here to view the first page.

The Structure of Your Source Code

main.m is the source code of your application. Source code is like a list of instructions to tell the computer what you want it to do.

However, a computer cannot run source code directly. Computers only understand a language called machine code, so there needs to be an intermediate step to transform your high-level source code into instructions that the CPU can carry out. Xcode does this when it builds and runs your app by compiling your source code. This step processes the source code and generates the corresponding machine code.

If this sounds complicated, don’t worry — you don’t need to know anything about the machine language part other than to know it’s there. Both you and the compiler understand Objective-C code, so that’s the common language you’ll use to communicate.

At the top of main.m, you’ll see several lines beginning with two slashes (//), as shown in the screenshot below:

//
//  main.m
//  My First Project
//
//  Created by You on 4/18/13.
//  Copyright (c) 2013 You. All rights reserved.
//

These lines are comments and will be ignored by the compiler. Comments are used to document the code of your app and leave any tidbits of information that other programmers — or your future self — might find useful. Look at the middle of the file and you will see a perfect example of this:

// insert code here...
NSLog(@"I can write anything I want!");

The comment // insert code here... is part of the project template from Xcode. It doesn’t change how the program runs, but it was put there by some helpful engineer at Apple to help you understand the code and get started.

Import Statements

Directly below the comments at the top of main.m is the following line:

#import <Foundation/Foundation.h>

That line of code is known as an import statement. In Xcode, not everything has to be contained in one single file; instead, you can use code contained in separate files. The import statement tells the compiler that “when you compile this app, also use the code from this particular file”.

As you can imagine, developing for OS X and iOS requires a lot of diverse functionality, ranging from dealing with text, to making requests over a network, to finding your location on a map. Rather than include a veritable “kitchen sink” of functionality into every app you create, import statements allow you to pick which features you require for your app to function. This helps to decrease the size of your code, the processing overhead required, and compile time.

Apple bundles OS features into frameworks. The import statement shown above instructs the compiler to use the Foundation framework, which provides the minimum foundation (as the name suggests) for any app.

Here’s a bit of trivia for you: how many lines of code do you think Foundation/Foundation.h adds to your main.m file? 10? 1000? 100000? A million?

[spoiler title=”Foundation.h lines of code”]Almost 90000 lines! That means the compiler is chugging through 90000 lines of code to support your 20 lines of source code in main.m.[/spoiler]

The Main Function

Look at the line following the import statement:

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

This line declares a function called main. All of the code in your app that provides some type of processing or logic is encapsulated into functions; the main function is what kicks off the whole app.

Think of a function as a unit of code that accepts input and produces output. For example, a function could take an account number, look it up in a database, and return the account holder’s name.

The int part of int main means the return value of main returns an integer such as 10 or -2. The (int argc, const char * argv[]) bits in parentheses are the arguments, or inputs, to the function. You’ll revisit the arguments of a function a bit later on.

Immediately below int main is an open curly brace ({) which indicates the start of the function. A few lines down you’ll see the corresponding closing curly brace (}). Everything contained between the two braces is part of the main function.

Since Objective-C is a procedural language, your program will start at the top of main and execute each line of the function in order. The first line of main reads as follows:

@autoreleasepool {

Just like in main, curly braces are used to surround a group of related lines of code. In this case, everything between the braces are part of a common autorelease pool.

Autorelease pools are used to manage memory. Every object you use in an app will consume some amount of memory — everything from buttons, to text fields, to advanced in-memory storage of user data eats away at the available memory. Manual memory management is a tricky task, and you’ll find memory leaks in lots of code — even code written by expert programmers!

Instead of tracking all the objects that consume memory and freeing them when you’re done with them, autoreleasepool automates this task for you. Remember when you created your project in Xcode and checked “Use Automatic Reference Counting”? Automatic Reference Counting, or ARC, is another tool that helps manage memory in your app so you almost never need to worry about memory usage yourself.

You’ll recognize the next line; it’s the one that you edited to create a custom message:

NSLog(@"I can write anything I want!");

The NSLog function prints out text to the console, which can be pretty handy when you’re debugging your code. Since you can’t always tell exactly what your app is doing behind the scenes, NSLog statements help you log the actions of your app by printing out things like strings or the values of variables. By analyzing the NSLog output, you’ll gain some insight as to what your app is doing.

If you’re worried about your end user seeing NSLog statements on their iPhones, don’t fret — the end user won’t see the NSLog output anywhere in the app itself.

In programming, text inside double quotation marks is known as a string. A string is how you store words or phrases. In Objective-C, strings are prefixed with an @ sign.

Look at the end of the NSLog line, you’ll see that the line is terminated by a semicolon. What does that do?

The Objective-C compiler doesn’t use line breaks to decide when one “line” of code ends and when one begins; instead, semicolons indicate the end of a single line of code. The NSLog statement above could be written like this:

NSLog(
@"I can write anything I want!"
)
;

…and it would function in the same manner.

To see what happens when you don’t terminate a line of code with a semicolon, delete the semicolon at the end of the NSLog statement, then press the Run button. You’ll see the following error indicated in Xcode:

Error

The NSLog line is highlighted in red, and a message states "Expected ';' after expression". Syntax errors like this stop the compiler in its tracks, and the compiler won’t be able to continue until you fix the issue. In this case, the correction is simple: just add the semicolon at the end of the line, and your program will compile and run properly.

There’s just one more line of code to look at in main:

return 0;

This line of code is known as a return statement. The function terminates when this line is encountered; therefore any lines of code following the return statement will not execute. Since this is the main function, this return statement will terminate the entire program.

What does the “0” mean after the return statement? Recall that this function was declared as int main, which means the return value has to be an integer. You’re making good on that promise by returning the integer value “0”. If there are no actual values to be returned to the caller of this function, zero is typically used as the standard return value for a function to indicate that it completed without error.

Mike Jaoudi

Contributors

Mike Jaoudi

Author

Over 300 content creators. Join our team.