Learn to Code iOS Apps 2: Strings, Arrays, Objects and Classes
Part 2 of a series where you’ll learn to code iOS apps using Apple’s development tools. For complete beginners – no prior programming experience needed! By Mike Jaoudi.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Learn to Code iOS Apps 2: Strings, Arrays, Objects and Classes
30 mins
Welcome to Part 2 of the Learn to Code iOS Apps series! This series introduces you to the basics of programming with the goal of creating an iOS app; no prior programming experience is required.
In the first tutorial in the series, you learned the basics of programming in Objective-C. Specifically:
- In Part 1, you learned the basics of Objective-C programming and you created a simple command line number guessing game.
- In Part 2 (You are Here!), you will learn about objects and classes in Objective-C and you will create a simple app to track people’s names and ages.
- In Part 3, the real fun begins! Now that you know the basics of programming, you will take all that you’ve learned and create a simple iPhone game of your own.
- In Part 4, you will take this app and make it beautiful, learning more about customizing the look and feel of iPhone apps.
Welcome to Part 2 of the Learn to Code iOS Apps series! This series introduces you to the basics of programming with the goal of creating an iOS app; no prior programming experience is required.
This part builds on the basic concepts that were covered in Part 1. If you haven’t worked through Part 1 yet and are new to programming or Objective-C, it’s highly recommended that you do so.
In this part you will learn about strings, arrays, classes, and objects in Objective-C. You will create will a Mac OS X app that keeps track of a list of people’s names and ages in order to learn these concepts.
These are fundamental building blocks that you will use in Part 3 of this series when you begin your iOS adventures in earnest and create your very first iPhone app!
Getting Started
This time you’re going to create a completely new project. You’ll choose a OS X command line app so you can continue to focus on the basics. Don’t worry – you’ll make an app with a user interface next time!
Start by launching Xcode and creating a new project by navigating to File\New\Project….
In the left column under OS X click on Application, select Command Line Tool, and click Next, as shown in the screenshot below:
Fill in the project options as follows:
- Product Name: PeopleDatabase
- Organization Name: This can be left blank.
- Company Identifier: Enter com.yourname
- Type: Foundation
- Use Automatic Reference Counting: Check this box
When you have finished filling out the information, the dialog should look similar to the one pictured below:
Just as in the previous project, you will add all your code inside the @autoreleasepool
block of main.m — right where the comment says insert code here
.
Working with Objects
Objective-C is known as an object-oriented language. But what is an object?
You’ve worked with variables containing primitive data types, such as int
, which holds an integer value. And that’s it. Primitive types don’t do anything beyond storing a single value.
However, objects extend this model by allowing multiple properties or values. For example, a button object might have a size, a color, and a label. Objects can also perform actions; for example, an image object could resize itself or draw itself on the screen.
Generally the type of an object is not referred to as a type, but rather a class. For example, consider the two following lines of code:
int age = 40;
NSString *name = @"Mike";
In plain language, you would describe age
as being “a variable of type int
“. However, you would describe name
as being “an object of class NSString
“, or alternately as “an instance of class NSString
“.
Note: Notice that there is a star (*) before the variable name this time. Whenever you create new objects, you always have to put a star when declaring the variable names. You can think of this as meaning “pointer to”, so you can say “name
is a pointer to an NSString
.”
Note: Notice that there is a star (*) before the variable name this time. Whenever you create new objects, you always have to put a star when declaring the variable names. You can think of this as meaning “pointer to”, so you can say “name
is a pointer to an NSString
.”
Now that you understand the terminology, the best way to understand objects and classes is to dive right in and start using them.
Working with Strings
A string is used to store text; it can be a single letter, a word, phrase, or even an entire book’s worth of text!
Look at the NSLog
included in main.m:
NSLog(@"Hello World");
In this line of code, @"Hello World!"
is a string.
In Part 1 of this series, you printed out the value of an int
variable using NSLog
. You can also print out strings in the same manner.
Replace the NSLog(@"Hello World");
line with the following two lines of code:
NSString *helloString = @"Hello Variable!";
NSLog(@"%@", helloString);
The first line declares a helloString
variable which holds an object of class NSString
, which is the basic string class in Objective-C. (Don’t worry about the *
character for now; just remember that when you declare an object variable, you need to prefix the variable’s name with an *
.)
The second line is the now-familiar NSLog
statement. But this time, instead of using %i
as the format specifier, you use %@
to specify that you wish to print out a string.
Run your app; the output should say ‘Hello Variable!’.
Note: Why does everything in Objective-C seem to be prefixed with “NS”? When Steve Jobs left Apple in the mid-1980s he started a company called NeXT. NeXT created the Objective-C language along with an operating system called NeXTSTEP.
Objects in Objective-C were prefixed with “NS” — short for NeXTSTEP. When Apple bought NeXT in 1996, they developed OSX and iOS on top of the existing NeXTSTEP frameworks — and almost 20 years later, we’re all still using class names from the NeXT era.
Note: Why does everything in Objective-C seem to be prefixed with “NS”? When Steve Jobs left Apple in the mid-1980s he started a company called NeXT. NeXT created the Objective-C language along with an operating system called NeXTSTEP.
Objects in Objective-C were prefixed with “NS” — short for NeXTSTEP. When Apple bought NeXT in 1996, they developed OSX and iOS on top of the existing NeXTSTEP frameworks — and almost 20 years later, we’re all still using class names from the NeXT era.
String objects can store more than simple static content. Find the two following lines of code:
NSString *helloString = @"Hello Variable!";
NSLog(@"%@", helloString);
…and replace them with the following code:
int x = 10;
NSString *myString = [NSString stringWithFormat:@"The variable x stores the number %i", x];
NSLog(@"%@", myString);
Take a look at each line of code separately. The first line is pretty straightforward; it assigns a value of 10 to the int
variable x
.
The second line is a bit more involved. In Objective-C, you tell an object to perform an action by sending it a message. The square brackets indicate that a message will be sent to the receiving object. Inside the square brackets, the message receiver NSString
is stated first, followed by the stringWithFormat:
message.
The NSString
class will receive the message and then see if it knows what stringWithFormat:
means. Luckily, the programmers at Apple have included the stringWithFormat:
method in NSString. stringWithFormat:
simply creates a new string from a format string and some parameters.
A method is a task or operation that you want to execute; it’s a block of code stored somewhere else that you can execute to perform a specific task. Note the colon at the end of the method name stringWithFormat:
; everything following the colon is considered an argument to the method call.
Most object-oriented programming languages use the terminology “calling a method on an object” rather than “sending a message to an object”. Many Objective-C programmers use this terminology as well. Unless you want to get really picky, you can consider “calling methods” and “sending messages” to be the same thing.
Finally, the third line simply outputs the formatted myString
object to the console.
Run your project, and verify that the output reads as follows:
The variable x stores the number 10
In Part 1, you read in the user’s input using scanf
. Sadly, you can’t use scanf
to read in a string, as scanf
doesn’t work on objects. It works only on primitive datatypes such as:
- int
- float
- BOOL
- char
What to do?
Technically a string is made up of a sequence of individual characters. So to accept string input, you can read in the sequence of characters and convert it to a string.
Add the following code directly below the line NSLog(@"%@", myString);
:
NSLog(@"Please enter a word.");
// 1
char cstring[40];
// 2
scanf("%s",cstring);
// 3
NSString *inputString = [NSString stringWithCString:cstring encoding:1];
NSLog(@"You entered the word '%@'", inputString);
Here’s an explanation of the above code, comment by comment:
- You declare a variable called
cstring
to hold 40 characters. - You then tell
scanf
to expect a list of characters by using the%s
format specifier. - Finally, you create an
NSString
object from the list of characters that were read in.
Run your project; if you enter a word and hit Enter, the program should print out the same word you typed. Just make sure the word is less than 40 characters; if you enter more, you might cause the program to crash — you are welcome to test that out yourself! :]