How do I make and use a Queue in Objective-C?

后端 未结 10 1243
栀梦
栀梦 2020-11-27 10:21

I want to use a queue data structure in my Objective-C program. In C++ I\'d use the STL queue. What is the equivalent data structure in Objective-C? How do I push/pop ite

10条回答
  •  北海茫月
    2020-11-27 10:49

    As far as I know, Objective-C does not provide a Queue data structure. Your best bet is to create an NSMutableArray, and then use [array lastObject], [array removeLastObject] to fetch the item, and [array insertObject:o atIndex:0]...

    If you're doing this a lot, you might want to create an Objective-C category to extend the functionality of the NSMutableArray class. Categories allow you to dynamically add functions to existing classes (even the ones you don't have the source for) - you could make a queue one like this:

    (NOTE: This code is actually for a stack, not a queue. See comments below)

    @interface NSMutableArray (QueueAdditions)
    
    - (id)pop;
    - (void)push:(id)obj;
    
    @end
    
    @implementation NSMutableArray (QueueAdditions)
    
    - (id)pop
    {
        // nil if [self count] == 0
        id lastObject = [[[self lastObject] retain] autorelease];
        if (lastObject)
            [self removeLastObject];
        return lastObject;
    }
    
    - (void)push:(id)obj
    {
         [self addObject: obj];
    }
    
    @end
    

提交回复
热议问题