Objective C - Manual Array FIFO Queue

后端 未结 2 1991
执念已碎
执念已碎 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:23

    Array with FIFO manner:

    if (mutArr.count == 5) {
            for (int j = 0; j < 4; j++) {
                [mutArr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
            [mutArr removeObjectAtIndex:4];
            [mutArr addObject:mutDict];
        }else{
            [mutArr addObject:mutDict];
        }
    
    0 讨论(0)
  • 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 <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];
    
    0 讨论(0)
提交回复
热议问题