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.

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

Working with Sets of Objects

Think back to Part 1 — how did you solve this problem in your Higher and Lower game? Ah — you can use a looping structure to repeat the same bits of code until the user is done.

Replace the code in the @autoreleasepool block in main.m with the following:

  @autoreleasepool {
    char response;

    do {
      Person *newPerson = [[Person alloc] init];

      [newPerson enterInfo];
      [newPerson printInfo];

      NSLog(@"Do you want to enter another name? (y/n)");
      scanf("\n%c", &response);
    } while(response == 'y');

  }

With this new code, in addition to asking for the name and age data, the program will now prompt the user to indicate if they are done. response can holds either a ‘y’ or ‘n’, depending on the user’s response.

You may have noticed that this while loop looks a little different than the one you used in Part 1. That’s because this is known as a do-while loop. The only difference here is that the looping condition is checked at the end of the loop, instead of at the beginning. This means that the code inside the loop will always execute at least once, regardless of the state of the looping condition.

Take a close look at the scanf statement in the above code. There’s a strange “\n” in there. What does that mean?

\n stands for “newline”, or the character that is printed when you hit the Enter key. It’s not a visible character, but scanf will still pick it up when it parses the user’s input. So \n%c is a special format specifier that tells scanf to read in a character discarding newlines and other whitespace characters such as a space or tab.

The looping condition at the end of the block checks if response is equal to the character ‘y’; if so, it loops back around. Note that the while condition has a semicolon after it; this is the only type of loop that requires a semicolon.

Run your project, and enter a few names and ages. As long as you keep typing “y”, the program will let you add another person. However, none of the names are being stored. Each time you go through the loop, a new Person object is created and the previous one is lost.

How do you go about storing multiple Person objects to retrieve later? You don’t want variables called person1, person2, person3, and so on — you have no idea how many you’ll need. Instead, you need to store them in some kind of list. To do that, you’ll use an array.

Working with Arrays

Arrays are a way of storing a bunch of objects in a list. There are two types of arrays in Objective-C: NSArray and NSMutableArray. NSArray is a basic static array; once you have created the array, you can’t add or remove items from it. This type of array is immutable, or unchangeable, much like many objects in Objective-C.

Conversely, NSMutableArray lets you add and remove items at any time. Since you will be adding an indeterminate number of people to the array over time, an NSMutableArray is a good choice in this situation.

Find the line that declares the response variable in main.m and add the following line directly below it:

NSMutableArray *people = [[NSMutableArray alloc] init];

The above line allocates and initializes a new NSMutableArray object called people.

Add the following line of code directly below the [newPerson printInfo]; line:

[people addObject:newPerson];

addObject: is a method of NSMutableArray that lets you add objects to the array. Now, each time you create a new Person object, you don’t have to worry about it disappearing — you simply add it to your people array so that it will remain in memory.

The storage mechanism of NSMutableArray is demonstrated by the image below:

DataLayout

That solves the problem of storing the Person objects — but how do you retrieve the objects once they’re stored? If you know the specific position, or index of the object in the array, you can reference the object by its index, as follows:

Person *theFirstPerson = people[0]

That code retrieves the first person in the array. Why are you using index “0” instead of “1”, you ask? Computers generally start indexing lists at zero, so the first element in the array is at position 0, the second element is at position 1, and so on.

In your app, you will loop through the array and print out all the stored names and ages only when the user has finished entering all of the data. This time you won’t use a while or dowhile loop — you’ll be using a for loop.

Add the following code after the line while (response == 'y');:

NSLog(@"Number of people in the database: %li", [people count]);
for (Person *onePerson in people) {
  [onePerson printInfo];
}

The NSLog line will print out the number of Person objects stored in the array using the count property of NSMutableArray.

The for loop starts at the beginning of the array and executes the code contained in the curly braces for each object found in the array. This is pretty handy, since now you really don’t need to know beforehand how many Person objects might be stored in the array.

Finally, the printInfo method of your Person object is used to print out each person’s information.

Run your project, and enter some information for a few people. When you are finished, the program will then neatly print out all of the people that you have stored in the array. Here’s a sample run of the program:

What is the first name?
John
What is John's last name?
Appleseed
How old is John Appleseed?
23
John Appleseed is 23 years old
Do you want to enter another name? (y/n)
y
What is the first name?
Albert
What is Albert's last name?
Einstein
How old is Albert Einstein?
76
Albert Einstein is 76 years old
Do you want to enter another name? (y/n)
n
Number of people in the database: 2
John Appleseed is 23 years old
Albert Einstein is 76 years old
Mike Jaoudi

Contributors

Mike Jaoudi

Author

Over 300 content creators. Join our team.