Objective C - 手动阵列FIFO队列 [英] Objective C - Manual Array FIFO Queue
问题描述
只是想知道创建手动数组的最佳方法,不使用NSMutalbleArray,我一直在研究最好的解决方案,但没有优雅的答案,你怎么想,在Objective C中什么是从中创建NSMutableArray样式对象的最佳方法刮?带有FIFO队列的
作为最终解决方案,即使是基本的阵列结构也是一个很好的提示!谢谢,
John
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
推荐答案
NSMutableArray上的类别是IMO最简单的方法。我有一个堆栈类别(LIFO)和队列(FIFO)
Categories on NSMutableArray is the easiest way IMO. I have a category for stacks (LIFO) and queues (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
制作和使用queue:
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];
这篇关于Objective C - 手动阵列FIFO队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!