7

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])
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
ludo
  • 1,479
  • 5
  • 25
  • 50

3 Answers3

11
if (j < [eventArray count])
{
     //Insert
}
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
3

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

Venk
  • 5,949
  • 9
  • 41
  • 52
bbum
  • 162,346
  • 23
  • 271
  • 359
0

I've given a brief implementation of a sparse array in this question: Sparse Array answer

Community
  • 1
  • 1
Jane Sales
  • 13,526
  • 3
  • 52
  • 57