iOS Friday Fundamentals: Arrays

Last night for our weekly iOS dev group I talked about and demonstrated the use of Arrays in iOS programming.

An array is pretty much just a list of data.  These lists can be useful for grouping together sets of information and iterating through them quickly.

An example: a classroom full of students would make a good “students” array.  The elements in that array would be the students, so our array might look like this:

students = [“Joe”, “Sarah”, “Sam”, “Pete”, “Lisa”, “John”, “Luke”, “Carmen”];

Aside from being atypically small, that’s a pretty normal looking classroom or group of students.  So, now that our students are together under the name “students”, we can go through them in an orderly list fashion.

We can access any given student within the array using their position in the array.  For example, the student “Sam” is at the 3rd position in the array.  Since arrays in iOS start with a count of 0, we will find “Sam” at position 2 in the array.  Confusing? Let’s look at it like this:

  • Joe = 0
  • Sarah = 1
  • Sam = 2
  • Pete =3…

So, Sam’s position in the “students” array is 2.

So how do we do this in Objective-C?

Arrays in Objective-C are called NSArray and NSMutableArray.  Mutable, as its definition would suggest, indicates that the array is changeable.

Without getting into the nitty-gritty of NSArray, I’ll show a quick snippet of the syntax that is used to create and populate an array.  (More details can be found in the Apple documentation on NSArray)

NSArray  * students = [NSArray arrayWithObjects:@"Joe",@"Sarah",@"Sam",@"Pete",@"Lisa",@"John",@"Luke",@"Carmen",nil];

Now, to quickly find out the total number of students or elements in the array, you just do the following:

int numberOfStudents  = [students count];  // returns 8

So, in this case, our student count is 8, but what if we’ve forgotten that “Jorge” joined the class late?  We need to add him to our current array, which we can do with:

[students addObject:@"Jorge"];

And now we’ve got 9 students and a happy class!

That’s all for today! Suggestions and comments are more than welcome as always.

*note- The guys over at iCodeBlog have a nice tutorial on NSArrays that’s probably worth checking out:

One Response to iOS Friday Fundamentals: Arrays

Leave a Response