pratik
pratik

Reputation: 4479

NSMutable Array

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.

Upvotes: 0

Views: 811

Answers (5)

puneet kathuria
puneet kathuria

Reputation: 720

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...

}

Upvotes: -2

prakash
prakash

Reputation: 59669

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

Upvotes: 2

zaph
zaph

Reputation: 112857

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

Returns the number of objects currently in the receiver.

- (NSUInteger)count

int arrayEntryCount = [temp count];

Upvotes: 0

bpapa
bpapa

Reputation: 21497

Check the length first using the count method.

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

Upvotes: 4

unknown
unknown

Reputation:

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.

Upvotes: 13

Related Questions