我有NSMutableArray并使用它像队列等待操作.
数组中的示例:
0:"做点什么"
1:"做别的事"
2:"做点什么2"
当我使用[myarray removeObjectAtIndex:0]
数组时没有重新排序,下次当我使用[myarray objectAtIndex:o]
结果时nil
.
当我删除"做某事"时,如何在第一个索引中添加"Do something else"和在第二个索引中添加"do something 2"?
/* gcc -framework Cocoa myprogram.m -o myprogram */ #importint 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 ] ); }
我通常以相反的顺序处理我的队列但效果是一样的:
// somewhere in your code you insert into the queue (always at index 0) [myArray insertObject:anObject atIndex:0];
然后,在其他地方,你从队列中读取:
// 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]; }