Objective C - Manual Array FIFO Queue

arrays, ios, objective-c

Solution

Categories on NSMutableArray is the easiest way IMO. I have a category for stacks (LIFO) and queues (FIFO)

Header

#import <Foundation/Foundation.h>

@interface NSMutableArray (QueueStack)
-(id)queuePop;
-(void)queuePush:(id)obj;
-(id)stackPop;
-(void)stackPush:(id)obj;
@end

Implementation

#import "NSMutableArray+QueueStack.h"

@implementation NSMutableArray (QueueStack)
// Queues are first-in-first-out, so we remove objects from the head
-(id)queuePop {
  @synchronized(self)
  {
    if ([self count] == 0) {
        return nil;
    }

    id queueObject = [[[self objectAtIndex:0] retain] autorelease];

    [self removeObjectAtIndex:0];

    return queueObject;
  }
}

// Add to the tail of the queue
-(void)queuePush:(id)anObject {
  @synchronized(self)
  {
    [self addObject:anObject];
  }
}

//Stacks are last-in-first-out.
-(id)stackPop {
  @synchronized(self)
  {
    id lastObject = [[[self lastObject] retain] autorelease];

    if (lastObject)
        [self removeLastObject];

    return lastObject;
  }
}

-(void)stackPush:(id)obj {
  @synchronized(self)
  {
    [self addObject: obj];
  }
}
@end

To Make and use a queue:

NSMutableArray *queue = [NSMutableArray array];

//Put an item in the queue
[queue queuePush:myObj];

//Retrieve an item, (this will be the first one)
MyCoolObject *myObject = [queue queuePop];

Problem

Just wondering the best way to create a manual array, without using NSMutalbleArray, I have being researching best possible solutions but without an elegant answer, what do you think, in Objective C what's the best way to create an NSMutableArray style object from scratch? with a FIFO queue as the final solution, even a basic array structure would be a great hint! thanks, John

Original source