Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Check the length first using the count method.

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

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];
}

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

Returns the number of objects currently in the receiver.

- (NSUInteger)count

int arrayEntryCount = [temp count];

First of all you check the length of array-

NSMutableArray *temp = //get list from somewhere.

now check- if(temp length) {

Your objectclass *obj = [temp objectAtIndex:indexnumber];

// indexnumber is 0,1,2 ,3 or anyone...

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top