views:

150

answers:

4

Hello,

I have a NSMutableArray:

NSMutableArray *temp = //get list from somewhere.

Now there is one method objectAtIndex which returns the object at specified index.

What I want to do is that, I want to first check whether an object at specified index exists or not. If it exists than I want to fetch that object. Something like:

if ([temp objectAtIndex:2] != nil)
{
     //fetch the object
}

But I get exception at the if statement saying that index beyond bound.

Please anyone tell me how to achieve this.

+13  A: 

you cannot have 'empty' slots in an NSArray. If [myArray count]==2 ie array has two elements then you know for sure that there is an object at index 0 and an object at index 1. This is always the case.

Continuing this thought, objectAtIndex: can never return nil. There cannot be nil objects in an array, and asking for something outside of the array raises an exception.
Rob Napier
i guess you can.. just by filling NSNull object ;)
Prakash
+1 for "you cannot have empty slots"
bpapa
Sorry, -1 for the same. As Prakash said, [NSNull null] can occupy a slot. It's sometimes important to have a 'null placeholder' for a missing object where 'position' is a design consideration.
Joshua Nozzi
[NSNull null] is an instance of an object that you can of course add to an array if you like, as you can any object. I can fill 1000,000 slots of an array with 14 megapixel NSImage instances if i like and call that 'empty'. If you try to access an index beyond the bounds of an array you will in no way get back an instance of NSNull. You will get an exception.
+4  A: 

Check the length first using the count method.

if ([temp count] > indexIWantToFetch)
    id object = [temp objectAtIndex:indexIWantToFetch];
bpapa
A: 

Just check that the index is >= 0 and < count

Returns the number of objects currently in the receiver.

- (NSUInteger)count

int arrayEntryCount = [temp count];
zaph
+2  A: 

you could do this way:

When you initialize, do something like:

NSMutableArray *YourObjectArray = [[NSMutableArray alloc] init];
for(int index = 0; index < desiredLength; index++)
{
   [YourObjectArray addObject:[NSNull null]];
}

Then when you want to add but check if it already exists, do something like this:

YourObject *object = [YourObjectArray objectAtIndex:index];
if ((NSNull *) object == [NSNull null]) 
{
    /// TODO get your object here..

    [YourObjectArray replaceObjectAtIndex:index withObject:object];
}
Prakash
You *could* do it this way, but why on earth would you want to?
Peter Hosey
There are plenty of cases where a "null placeholder" is useful in an array. Prakash is correct in saying it's possible to add [NSNull null] to an array. In one case I had to solve, position-dependent array of numerical values could have "missing values". "Missing value" is not the same as [NSNumber numberWithInt:0] ...
Joshua Nozzi