如何将NSMutableArray用作队列?

时间:2009-02-05 20:31:13

标签: cocoa

我有NSMutableArray并且像队列一样用它来等待行动。

数组中的示例:

0:“做点什么”
1:“做别的事”
2:“做点什么2”

当我使用[myarray removeObjectAtIndex:0]时,数组不会重新排序,下次使用[myarray objectAtIndex:o]时,结果为nil

当我删除“做某事”时,如何在第一个索引中添加“Do something else”并在第二个索引中添加“do something 2”?

5 个答案:

答案 0 :(得分:10)

/* 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 ] );
}

答案 1 :(得分:8)

我通常以相反的顺序处理我的队列但效果是一样的:

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

答案 2 :(得分:3)

NSArray已经按照您想要的方式运行,实际上不能包含nil。听起来你的数组可能会以某种方式设置为nil。

答案 3 :(得分:1)

我假设您在迭代时没有删除...

答案 4 :(得分:0)

  

当我使用[myarray removeObjectAtIndex:0]时,数组没有重新排序,下次当我使用[myarray objectAtIndex:o]时,结果为nil。

你的问题似乎是你有一个小写字母O而不是数字0