01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Arrays<br />

77<br />

On return, the variable numberOfItems tells you how many elements are in the array.<br />

To access each element in an NSArray, you can use another message called objectAt-<br />

Index:, which behaves similarly to the [] indexing operator used with C-style arrays:<br />

id item = [myArray objectAtIndex:5];<br />

You could imagine this last statement as being equivalent to myArray[5] if myArray<br />

had instead been declared as a C-style array. The intent and behavior is identical.<br />

Using the techniques you learned in this section, you could access the last element of<br />

an array with the following code snippet:<br />

int indexOfLastItem = [myArray count] - 1;<br />

id item = [myArray objectAtIndex:indexOfLastItem];<br />

You could even condense this into a single statement by nesting the two method calls:<br />

id item = [myArray objectAtIndex:[myArray count] - 1];<br />

The -1 in the index calculation accounts for the fact that the last element in the array<br />

will have an index of 1 less than the number of items in the array. Because this is a<br />

common code pattern and Foundation Kit is all about developer efficiency, NSArray<br />

provides a lastObject message that performs the same task in a cleaner manner:<br />

id item = [myArray lastObject];<br />

Using this concept of simplifying common coding tasks, let’s investigate some of the<br />

other aspects of the NSArray class.<br />

4.1.3 Searching for array elements<br />

You now have the building blocks for determining if a particular value is present in an<br />

array. To achieve this goal, you can use a for loop to step through each element in the<br />

array and use an if statement to compare the current element with the value you’re<br />

looking for. This process is demonstrated in the following listing.<br />

Listing 4.2<br />

Determining if an NSArray contains the word “Fish” using C-style code<br />

NSArray *pets = [NSArray arrayWithObjects:@"Cat", @"Dog", @"Rat", nil];<br />

NSString *valueWeAreLookingFor = @"Fish";<br />

int i;<br />

BOOL found = NO;<br />

for (i = 0; i < [pets count]; i++)<br />

{<br />

if ([[pets objectAtIndex:i]<br />

isEqual:valueWeAreLookingFor])<br />

{<br />

found = YES;<br />

break;<br />

}<br />

}<br />

B<br />

d<br />

Step through<br />

the array<br />

c<br />

Check array<br />

element value<br />

Break out<br />

for loop<br />

if (found)<br />

{

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!