Objective C - Manual Array FIFO Queue

后端 未结 2 1994
执念已碎
执念已碎 2021-02-11 02:15

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

2条回答
  •  太阳男子
    2021-02-11 02:45

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

    Header

    #import 
    
    @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];
    

提交回复
热议问题