Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether data is present at an index in NSMutableArray

I have a NSMutableArray, I want to insert data inside it, the problem is first I want to check if the index where I'm inserting the data exists or not. How to do that? I try something like that but nothing is working:

if ([[eventArray objectAtIndex:j] count] == 0)

or

if (![eventArray objectAtIndex:j])
like image 345
ludo Avatar asked Feb 26 '10 08:02

ludo


2 Answers

if (j < [eventArray count])
{
     //Insert
}
like image 195
willcodejavaforfood Avatar answered Sep 29 '22 13:09

willcodejavaforfood


NSArray and NSMutableArray are not sparse arrays. Thus, there is no concept of "exists at index", only "does the array have N elements or more".

For NSMutableArray, the grand sum total of mutable operations are:

- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;

All other mutability methods can be expressed in terms of the above and -- more specifically to your question -- removing an object does not create a hole (nor can you create an array with N "holes" to be filled later).

like image 20
bbum Avatar answered Sep 29 '22 14:09

bbum