我有NSMutableArray和使用它像隊列等待行動。如何使用NSMutableArray作爲隊列?
實施例中陣列:
0: 「做什麼」
1: 「做別的事情」
2: 「做什麼2」
當我使用[myarray removeObjectAtIndex:0]
排列並不重排序和下一次我使用[myarray objectAtIndex:o]
的結果是nil
。
當我刪除「做某事」時,如何在第一個索引中放入「做別的事」,如何在第二個索引中放入「做某事2」?
我有NSMutableArray和使用它像隊列等待行動。如何使用NSMutableArray作爲隊列?
實施例中陣列:
0: 「做什麼」
1: 「做別的事情」
2: 「做什麼2」
當我使用[myarray removeObjectAtIndex:0]
排列並不重排序和下一次我使用[myarray objectAtIndex:o]
的結果是nil
。
當我刪除「做某事」時,如何在第一個索引中放入「做別的事」,如何在第二個索引中放入「做某事2」?
NSArray已經按照你想要的方式工作,實際上不能包含零。這聽起來像你的數組可能會設置爲零。
我假設在迭代你不刪除...
/* 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 ]);
}
唯一的問題是你可能期望一個數組彈出來返回彈出的對象,但removeObjectAtIndex不會返回任何東西。 – 2013-10-29 05:38:19
我通常如何處理我的隊列,以相反的順序,但效果是一樣的:
// 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];
}
當我用[myArray的[R emoveObjectAtIndex:0]數組不重新排序,下一次當我使用[myarray objectAtIndex:o]結果爲零。
你的問題似乎是,你有一個小寫O和數量不限0
這隻會導致編譯錯誤......除非提問者實際上有一個名爲`o`的變量,在這種情況下,提問者會得到一個有效的對象(儘管可能不是提問者期望的那個)或一個NSRangeException。 – 2009-11-09 02:53:52
你可以發佈一個代碼示例演示什麼是不工作? removeObjectAtIndex:應該完成你想要的。 – 2009-02-05 20:38:15