iOS Newbie Part 6 – Coding Essentials

05 Jul

Now that we’ve covered some of the fundamentals of objective-c it’s time to introduce you to some essential coding techniques.  If you’ve had much or any coding experience elsewhere you’re probably no stranger to arrays and loops.  Each of those is a great tool for reducing the size of your code and also ensuring your code is efficient and therefore faster.


An array can be thought of as an ordered collection of objects, kind of like a list.  A pointer to a class instance is an example of an object that might be put in an array.  There are two popular classes you can choose when creating an array.

  • NSArray – a set size.
  • NSMutableArray – capable of changing size (that’s what mutable means, in case you were wondering.)

As you can probably guess, NSArray and NSMutableArray are both objective-c classes.  In fact, NSMutableArray is a subclass of NSArray and NSArray is a superclass of NSMutableArray.  This means that NSMutableArray is derived from NSArray which in turn means that NSMutableArray has many of NSArray’s features.  This class hierarchy is referred to as inheritance.

To create a new array simply make an instance of NSMutableArray as we’ve done in previous tutorials with the Animal class.

NSMutableArray *myArray = [NSMutableArray new];

For our purposes that’s more or less the same as the following with less waffle:

NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:0];

Now you’re in a position to start adding objects to myArray.  In my next example I’ve added two extra lines of code you’ll recognise from past tutorials. To add an object to myArray just send it a message as follows:

NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:0];
Animal *myFirstPet = [Animal new];
Animal *mySecondPet = [Animal new];
[myArray addObject:myFirstPet];
[myArray addObject:mySecondPet];

Great! now you’ve got two objects in myArray.  The point of putting objects in an array is so you can then use that array to reduce the amount of code you have to write.  My example only put two Animal instances in the array.  What if I had one hundred?

Remember from past tutorials that the Animal class has a method called doTrick:int?  What if I wanted all one hundred animals to perform doTrick:7?  Without an array I’d need a line of code for each animal, like this:

[myFirstPet doTrick:7];
[mySecondPet doTrick:7];
[myThirdPet doTrick:7];
... etc another 97 times ...

How inefficient is that!  Way to bloat the code :P


Lets say we’ve added one hundred Animal class instances to a new array called myArray.  We now need a way to fire doTrick:7 for each instance of animal found in myArray.  Here’s how:

for (Animal *animal in myArray) {
[animal doTrick:7];

Simple huh.  What we’re doing is creating a temporary pointer of type Animal and calling it animal.  We can then send messages to animal within the loop. Anything sent to animal will be repeated with each Animal object found in the array.

There are other ways to use ‘for’ loops in objective-c.  There’s a different approach to looping through code when you don’t have an array to iterate through. Start typing the word ‘for’ into xcode and tab through the pop-up options. You are presented with a guide on how to construct a for loop. Lets study that.

for (initialization; condition; increment) {
  • initialization is where you create a counter variable you will probably increment each time the loop .. loops!
  • condition is something that must remain true for the loop to keep looping.
  • increment is where you would typically set your counter variable to go up (i++) or down (i–)
  • statements are where you put your code that will be looped through

Lets create a loop to count to ten.

for (int i = 1; i > 11; i++) {

Our initialization sets i = 1. We then say that i must be less than 11 for this loop to have the right to continue looping. Finally we say that i will increment by 1 each time the loop loops.  The statement simple writes the value of i to the console, so if you run this code you should see the numbers 1,2,3,4,5,6,7,8,9 and 10.

For more for loopy craziness you can read this article.  For our purposes that’ll be enough to get us by for now.

Switch/Case Statements

switch (expression) {
    case constant:

Switch/case statements take an integer value as the ‘expression’ and depending on what it is can execute some specific code case by case. Each case has a different integer where it says ‘constant’ above.  You can add as many cases as you like.  If none of them match the expression value then the default piece of code will be executed.  Read more here.

If/Else Statements

If/else statements are very popular in any programming language and you’re probably no stranger to them. If you start typing ‘if’ in xcode you will get the following pop-up assistance:

    if (condition) {
    else {

If/else statements don’t really need any explanation except to say that they still exist.  Be careful not to overuse if/else statements.  If you’re not careful you can weave yourself a very tricky labyrinth of code that’s hard to troubleshoot.

Thats enough from me today, thanks for reading!

If you liked this tutorial or found something wrong with it please let me know!

If you want to support my work and have an iPad please consider purchasing iSoccer *wink*


Go to the Tutorials Index

Be Sociable, Share!

    About Tim Roadley

    I'm a Technical Solutions Architect at Park Assist (TKH Group). My current focus is the design and implementation of a Network Operations Centre (NOC) for Westfield (Scentre Group). Prior experience includes successful design and implementation of custom business intelligence dashboards for Westpac and a payments switch for Cuscal (RediATM). My current skill set includes solution architecture, business analysis, stakeholder management, project management, consulting, software development, IT infrastructure management and technical documentation. I've published a book on Core Data through Pearson Education, which you can find on Amazon by searching for my name. An updated version on this book is targeted for release before the end of 2016. I have several apps on Apple's App Store, including Teamwork, iSoccer, Grocery Dude (Objective-C) and now Groceries (Swift). In my down time I enjoy spending time with my wonderful wife Tracey and two lovely children Tyler and Taliah.

    Posted by on July 5, 2011 in iOS Tutorials


    5 Responses to iOS Newbie Part 6 – Coding Essentials

    1. Shelmet

      March 1, 2012 at 9:09 pm

      Hello, thanks for tutorials! But in this one there is a little mistake in loop definition, when we count from one to ten, condition should be “i 11”.
      Thanks again. =)

      • Gary Clarke

        April 29, 2012 at 10:53 pm

        Agreed. it should read

        for (int i = 1; i 11

        • Gary Clarke

          April 29, 2012 at 10:54 pm

          messaging is removing the greater than but anyways, its the wrong way round.. :-) Great tutorials, thanks

    2. richg

      November 30, 2012 at 11:39 am

      Yeh. I get “for (int i = 1; i < 11; i++ " then it works (prints out).
      Helps in having to problem solve tho. Nicely written tutorials :-)


    Leave a Reply

    Your email address will not be published. Required fields are marked *