I want to use a queue data structure in my Objective-C program. In C++ I\'d use the STL queue. What is the equivalent data structure in Objective-C? How do I push/pop ite
As far as I know, Objective-C does not provide a Queue data structure. Your best bet is to create an NSMutableArray
, and then use [array lastObject]
, [array removeLastObject]
to fetch the item, and [array insertObject:o atIndex:0]
...
If you're doing this a lot, you might want to create an Objective-C category to extend the functionality of the NSMutableArray
class. Categories allow you to dynamically add functions to existing classes (even the ones you don't have the source for) - you could make a queue one like this:
(NOTE: This code is actually for a stack, not a queue. See comments below)
@interface NSMutableArray (QueueAdditions)
- (id)pop;
- (void)push:(id)obj;
@end
@implementation NSMutableArray (QueueAdditions)
- (id)pop
{
// nil if [self count] == 0
id lastObject = [[[self lastObject] retain] autorelease];
if (lastObject)
[self removeLastObject];
return lastObject;
}
- (void)push:(id)obj
{
[self addObject: obj];
}
@end