Does the iOS SDK provide queues and stacks?

Tommy Herbert picture Tommy Herbert · Sep 6, 2010 · Viewed 27.6k times · Source

I'm writing an iPhone app, and I'm surprised that there seem to be no NSQueue or NSStack classes in Apple's Foundation Framework. I see that it would be quite easy to roll my own, starting with an NSMutableArray, so I'll do that unless I've missed something. Have I missed something?

Answer

Tommy Herbert picture Tommy Herbert · Sep 10, 2010

Here's my Stack class, in case it's useful to those who come after me. As you can see, the pop method involves enough code that you'd want to factor it out.

Stack.h:

#import <Foundation/Foundation.h>

@interface Stack : NSObject {
    NSMutableArray *contents;
}

- (void)push:(id)object;
- (id)pop;

@end

Stack.m

#import "Stack.h"

@implementation Stack

// superclass overrides

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

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

// Stack methods

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

- (id)pop {
    id returnObject = [[contents lastObject] retain];
    if (returnObject) {
            [contents removeLastObject];
    }
    return [returnObject autorelease];
}

@end