NSMutableArray, indexOfObject:, NSNull and NSNotFound (Xcode for iOS)

Creating an array with empty objects

NSMutableArray is a useful class for ordering objects and keeping them in order. So let's suppose we have a set number of items, for example pages in a book. We might want to place each view, or view controller, that represents a page in the book at the correct place in the array, but not necessarily want all of the pages to be held in the array at one time.

So first of all we need an array of empty objects. And let's say we'd like it to be 20 objects long.

NSMutableArray *pagesArray = [[NSMutableArray alloc] init];
int i = 0;
for (i < 20)
 {
[pagesArray addObject:[NSNull null]]
i++;
}

Replacing empty objects with real ones

Now we have an array into which we can insert our page objects at their correct places.

[pagesArray replaceObjectAtIndex:10 withObject:page11]

Of course in real use we would've instantiated whatever it is our page11 object is, but for now it's the array we're interested in.

Knowing where things are in the array

Now we get to the really useful stuff. Suppose you've added a subview to your current view, or the app's done this for you in some way, or the user has. And we now want to know which page is currently displayed. Instead of guessing, we simply ask pagesArray for the answer because whichever page it is we would've placed it in the correct place when it went onscreen and after that we forgot about keeping track of it, because we didn't need to instead we just call indexOfObject: to do the work and tell us where it is in the array and from that we will know the page number, like this:

[pagesArray indexOfObject:pageView]

How we get the pointer to the view isn't discussed here but we can either cycle through the subviews or we'll have some kind of pointer retaining it. We might alternatively be passed a view or view controller in a method by the system and not know whether or not the view is in our list of pages at all.

When to use NSNotFound

If we don't know whether or not the page is in our array we again use indexOfObject but we can't use it to test like you might thing:

if ([pagesArray indexOfObject:pageView]) {
//do something
}

This is because indexOfObject always returns a number. It's just that if the item isn't in the array then the number is the maximum possible number, which we test for with NSNotFound. So we'd know if a page was not in our array by testing in this way:

if ([pagesArray indexOfObject:pageView]==NSNotFound) {
//the page isn't in our array
}
else {
//the page is in our array
}

Endorse on Coderwall

Comments