Search code examples
objective-ccocoadata-structuresqueue

How do I make and use a Queue in Objective-C?


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 items?


Solution

  • Ben's version is a stack instead of a queue, so i tweaked it a bit:

    NSMutableArray+QueueAdditions.h

    @interface NSMutableArray (QueueAdditions)
    - (id) dequeue;
    - (void) enqueue:(id)obj;
    @end
    

    NSMutableArray+QueueAdditions.m

    @implementation NSMutableArray (QueueAdditions)
    // Queues are first-in-first-out, so we remove objects from the head
    - (id) dequeue {
        // if ([self count] == 0) return nil; // to avoid raising exception (Quinn)
        id headObject = [self objectAtIndex:0];
        if (headObject != nil) {
            [[headObject retain] autorelease]; // so it isn't dealloc'ed on remove
            [self removeObjectAtIndex:0];
        }
        return headObject;
    }
    
    // Add to the tail of the queue (no one likes it when people cut in line!)
    - (void) enqueue:(id)anObject {
        [self addObject:anObject];
        //this method automatically adds to the end of the array
    }
    @end
    

    Just import the .h file wherever you want to use your new methods, and call them like you would any other NSMutableArray methods.