Objective-C FIFO queue



我想实现一个具有简单线程安全的FIFO队列类。我不想使用标准Objective-C框架中的任何类(NSObject除外),这意味着我不想使用NSMutableArray。

你能看出我的解决方案是否正确吗?谢谢!

#import <Foundation/NSObject.h>
@interface Queue : NSObject
{
    id _value;
    Queue *tail;
}
/* Puts an object at the end of the queue. The object is retained.  */
- (void) putObject: (id)object;
/* Gets an object from the beginning of the queue.  The object is
 * removed from the queue.  If there are no objects in the queue,
 * returns nil.  The object is autoreleased.
 */
- (id) getObject;
@end
@implementation Queue
- (id) init
{
    return self;
}
- (void) dealloc
{
    [super dealloc];
}
- (void) putObject: (id)object
{
    if(tail)
    {
        [tail putObject:object];
    }else{
        tail = [[Queue alloc]init];
        _object = object;
    }
}
- (id) getObject
{
    return _value;
}
@end

你能看出我的解决方案是否正确吗?谢谢!

你测试过吗?

您需要考虑的一些事项:

  • 快速阅读表明这是一个"先进先出"的设计......(看得到一个对象)
  • 添加对象需要太长时间(O(N) 与 O(1))
  • 如果您使用 ARC 进行内存管理会更好(您的[super dealloc]表明您正在使用 MRR/MRC)

听Josh Caswell在评论中,这不是这类问题的论坛。

最新更新