« The Storage Series, Part Two

Posted by Andy Monitzer on March 07, 2001 [Feedback (0) & TrackBack (1)]

// Part Two: Arrays

This article, the second in a series on the storage classes NSArray and NSDictionary, discusses the simpler of the two: arrays. You may be asking yourself "what is an array?" There are many ways in which you can think of or mentally picture an array.

One such way is to picture a chess board, with columns and rows. If we begin numbering the columns at 0 and go to 8, we could easily pinpoint the square at 3,7. Just like a cartesian coordinate system. In an array-style format, this might be ChessBoard[3][7]. This would be an example of a two-dimensional array.

What is an example of a one-dimensional array (the most common form)? A row of cars. A calendar. Suppose we associated a "quote of the day" with every day of the year. Accessing Quote[55] - the 55th element in the "quote" array - would give us the quote for February 24th.

But even that contains a slight falsity... In Objective-C, and many languages in fact, arrays begin at "item zero" or someArray[0]. So in fact, Quote[55] would give us the quote for February 25th, the 56th day of the year. Why? Because Quote[0] is January 1, and Quote[365] only exists in leap years, otherwise the last quote would be Quote[364].

 

// Get to It

Let's suppose you wish to store a list of names. If you have only three items, you could do something like this:

@interface MyClass : NSObject
{
	NSString *name1;
	NSString *name2;
	NSString *name3;
}
@end

This code would create a class called MyClass. If an object of type MyClass were instantiated, it would have instance variables called name1, name2, and name3. This might work great for three items, but what about hundreds of names? Thousands? Or worse, an unknown number? Some magic needs to be done here, and an array can handle it.

Arrays are useful because they need not be static. They can be easily traversed and manipulated in a for loop. Consider this:

int foo=[someArray count];
int i;

for(i=0; i<foo; i++)
{
    NSString *item=[someArray objectAtIndex:i];
    NSLog(@"Item %d: %@",i,item);
}

This code first checks to see how many elements are in the someArray array. Then, using a for loop, it prints the contents of the array, one by one, to the console (that's what NSLog does). This is an extremely simple example, but consider this: the elements in an array - the "things" in an array - need not be simple data like strings. They can be references to windows in your applications, buttons, checkboxes (but need to be objects that inherit from NSObject. Additionally, you could easily send the same message to each item in the array - such as toggling a checkbox - by using the special feature [someArray makeObjectsPerformSelector:@selector(setState:) withObject:NSOnState]. Of course, that's not all you can do with arrays... but you get the point!

 

// Work with Arrays

Well, that's what arrays do. You can create one using the line here:

NSArray *list=[[NSArray alloc] initWithObjects:@"Andy",@"Erik",@"Aaron",nil];

This example creates an array named "list" with the values "Andy", "Erik", and "Aaron". Note that this is a variable argument list: You can add any number of items you want, you just have to mark the end with 'nil'. If we make a little table of the index, it would appear as:

Index:      Item:
0           "Andy"
1           "Erik"
2           "Aaron"

Now suppose we would want to access the second item. Don't forget that counting starts at zero! We'd do that simply by using this command: NSString *name2=[list objectAtIndex:1];. This would stick the value "Erik" (a string) into the space at "name2".

Or, suppose we wanted to see how many items were in the array. We'd do that with: unsigned listCount=[list count];. You can even add an array (or any other object) to an array:

NSArray *innerList=[NSArray arrayWithObjects:@"One",@"Two",nil];
NSArray *outerlist=[[NSArray alloc] initWithObjects:innerList,@"Erik",nil];

Note: arrayWithObjects returns an autoreleased array, initWithObjects does not. Whenever an item gets added to an array, NSArray retains it, so you have to release it if you don't need it anymore. If you don't quite understand what retaining, releasing, and allocating/deallocating are... poke around this site for information on those topics. It's important, but isn't something we can cover here in this article on arrays!

 

// Mutable Additions

(If you don't know what 'mutable' and 'immutable' means, please read part one of this series.)

Let's take a look at an example. Let's suppose you want to dynamically add or remove items from your array? No problem:

NSMutableArray *list=[[NSMutableArray alloc] init];
[list addObject:@"new item!"];
[list addObject:@"another!"];
[list addObject:@"one more..."];
[list removeObjectAtIndex:0];

As you can see, we created an array named "list". We added the strings "new item!", "another!", and "one more...", then we removed the object at index 0 - the first element of the array. Now all that's left is "another!" and "one more..." because "new item!" was the first item in the array - the item at index 0.

Of course, this is a brief discussion on arrays. We could do much more, like adding an object at a particular index, sorting, and more... but those are also beyond the scope of this introductory article. Read the next part of the Storage Classes series for basic information on dictionaries.


Comments
Post a comment