tags:

views:

1159

answers:

5

Hi all,
I have NSMutableArray and used it like queue for waiting actions.

Example in array:

0: "Do something"
1: "Do something else"
2: "Do something 2"

When I used [myarray removeObjectAtIndex:0] the array is not reordering and next time when I use [myarray objectAtIndex:o] the result is nil.

How can I put "Do something else" in the first index and "Do something 2" in the second index when I remove "Do something"?

+3  A: 

NSArray already behaves the way you want, and in fact cannot contain nil. It sounds like your array might be somehow getting set to nil.

Chuck
+1  A: 

I assume you're not removing while iterating...

+5  A: 
/* gcc -framework Cocoa myprogram.m -o myprogram */

#import <Cocoa/Cocoa.h>

int main( int argc, char **argv )
{
  NSMutableArray *array = [ [ NSMutableArray alloc ] 
                           initWithObjects: @"1", @"2", @"3",
                                            nil ]; /* don't forget nil */

  /* "pop" the first object */
  [ array removeObjectAtIndex:0 ];

  /* prints "2" as expected */
  NSLog( @"%@", [ array objectAtIndex: 0 ] );
}
codelogic
+1  A: 

I normally handle my queues in the reverse order but the effect is the same:

// somewhere in your code you insert into the queue (always at index 0)
[myArray insertObject:anObject atIndex:0];

then, elsewhere, you read from the queue:

// Process elements in the queue in a FIFO manner
while ([myArray count])
{
    id object = [myArray lastObject];

    // do something with object

    [myArray removeObjectAtIndex:[myArray count] - 1];
}
Matt Gallagher
A: 

When I used [myarray removeObjectAtIndex:0] the array is not reordering and next time when I use [myarray objectAtIndex:o] the result is nil.

Your problem seems to be that you have a lower case O and not the number 0

frak
That would just cause a compile error… unless the questioner actually has a variable named `o`, in which case the questioner would get either a valid object (though perhaps not the one the questioner expects) or an NSRangeException.
Peter Hosey