3

只是想知道在不使用 NSMutalbleArray 的情况下创建手动数组的最佳方法,我一直在研究可能的最佳解决方案,但没有一个优雅的答案,您认为,在 Objective C 中,从头开始创建 NSMutableArray 样式对象的最佳方法是什么?使用 FIFO 队列作为最终解决方案,即使是基本的数组结构也会是一个很好的提示!谢谢,约翰

4

3 回答 3

16

NSMutableArray 上的类别是 IMO 最简单的方法。我有一个用于堆栈 (LIFO) 和队列 (FIFO) 的类别

标题

#import <Foundation/Foundation.h>

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

执行

#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

制作和使用队列:

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];
于 2012-10-29T20:41:19.720 回答
3

采用FIFO方式的数组:

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];
    }
于 2014-06-18T13:21:20.903 回答
1

即使我不理解 NSMutableArray 的问题,这里有一种方法可以使用双向链表实现队列(希望我做对了,我有点累了;)):

注意:我假设使用 ARC。

//Node.h
@interface Node : NSObject

@property (strong)id value;
@property (strong)Node *previous;
@property (strong)Node *next;


//Node.m
@implementation
@end


/Queue.h
@interface Queue : NSObject

- (void)enqueue:(id)objectToEnqueue;
- (id)dequeue;

@end

//Queue.m
@interface Queue ()
{
    Node *start;
}

@implementation

- (void)enqueue:(id)objectToEnqueue
{
    Node *node = [Node new];
    node.value = objectToEnqueue;

    if (nil == start)
    {
        node.previous = node;
        node.next = node;
        start = node;
    }
    else
    {
        node.previous = start.previous;
        node.next = start;
        start.previous = node;
        start = node;
    }
}

- (id)dequeue
{
    if (nil == start)
        return nil;

    Node *node = start.previous;

    start.previous = start.previous.previous;
    start.previous.next = start;

    id objectToDequeue = node.value;

    return objectToDequeue;

}
@end

如果您正在寻找一种在纯 C 中执行此操作的方法,也许这会对您有所帮助:

实现队列的 C 程序

于 2012-10-29T22:06:12.837 回答