2009-07-09 47 views

回答

10

基于NSMutableArray实现队列很容易,它可能在50行以下的代码。

编辑:

了快速谷歌搜索发现这一点:

@interface Queue:NSObject { 
    NSMutableArray* objects; 
} 
- (void)addObject:(id)object; 
- (id)takeObject; 
@end 

@implementation Queue 

- (id)init { 
    if ((self = [super init])) { 
     objects = [[NSMutableArray alloc] init];  
    } 
    return self; 
} 

- (void)dealloc { 
    [objects release]; 
    [super dealloc]; 
} 

- (void)addObject:(id)object { 
    [objects addObject:object]; 
} 

- (id)takeObject { 
    id object = nil; 
    if ([objects count] > 0) { 
     object = [[[objects objectAtIndex:0] retain] autorelease]; 
     [objects removeObjectAtIndex:0]; 
    } 
    return object; 
} 

@end 
+1

1我清理代码格式一点点,并且-takeObject方法。 – 2009-07-10 18:04:43

+0

在你的dealloc上添加一个[objects release]我会给你一个+1 – slf 2010-06-12 18:26:58

5

可可本身不具有Queue类,而且也没有一个标准本身,而是有多种选择,一个其中最适合您的需求。见this question(和my answer)。

就像你说的,你可以使用NSMutableArray推出自己的。如果你只需要一个quick'n'dirty队列(并不担心复制,编码/解码,枚举等),那么@Matt的解决方案是一个简单的方法。你还应该考虑adding queue methods to NSMutableArray via a category,这很好,因为你的“队列”也是一个数组(所以你可以将它传递给NSArray参数),并且你可以免费获得所有NS(可变)数组的功能。

如果性能很重要,我推荐使用更适合去除第一个元素的结构。出于这个原因,我为自己的框架写了CHCircularBufferQueue。 (不要试图自吹自擂,只是为了节省一些时间。)

1

我已经根据马特桥代码制作了一个只包含deque方法的类。

@interface NSMutableArray (ShiftExtension) 
// returns the first element of self and removes it 
-(id)shift; 
@end 

@implementation NSMutableArray (ShiftExtension) 
-(id)shift { 
    if([self count] < 1) return nil; 
    id obj = [[[self objectAtIndex:0] retain] autorelease]; 
    [self removeObjectAtIndex:0]; 
    return obj; 
} 
@end 
0

您可以使用C++标准库中的STL队列。

0

查看STL priority queue。它需要零线代码,并且是便携式的!你还能想要什么?

0

你可以使用:NSArray的lastObject方法。下面是一个未经测试的例子:

Queue.h

#import <Foundation/Foundation.h> 

@interface Queue : NSObject 

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

@end 

Queue.m

#import "Queue.h" 

@interface Queue() 

@property(nonatomic, strong) NSMutableArray *backingArray; 

@end 

@implementation Queue 

-(id)init { 
    self = [super init]; 

    if (self) { 
     self.backingArray = [NSMutableArray array]; 
    } 
    return self; 
} 

-(void)enqueue:(id<NSObject>)object { 
    [self.backingArray addObject:object]; 
} 

-(id)dequeue { 
    id object = [self.backingArray lastObject]; 
    [self.backingArray removeObject:object]; 
    return object; 
} 

@end