Does the iOS SDK provide queues and stacks? Does the iOS SDK provide queues and stacks? ios ios

Does the iOS SDK provide queues and stacks?

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.


#import <Foundation/Foundation.h>@interface Stack : NSObject {    NSMutableArray *contents;}- (void)push:(id)object;- (id)pop;@end


#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

as far as I know there is no generic class avaialbe. Try using the NSMutableArray, add via addObject and get first/last via objectAtIndex and removeObjectAtIndex.

Another easy way would be to extend NSMutableArray's capabilities by making use of Objective C's categories. You can do that by adding two files to your project:


@interface NSMutableArray (StackExtension)- (void)push:(id)object;- (id)pop;@end


#import "NSMutableArray+Stack.h"@implementation NSMutableArray (StackExtension)- (void)push:(id)object {    [self addObject:object];}- (id)pop {    id lastObject = [self lastObject];    [self removeLastObject];    return lastObject;}@end

Now you can use a regular NSMutableArray in every other file of your project like a stack and call push or pop on that object. Don't forget to #import NSMutableArray+Stack.h in those files. Here is some sample code how you can use your new NSMutableArray as a stack:

NSMutableArray *myStack = [[NSMutableArray alloc] init]; // stack size = 0NSString *aString = @"hello world";[myStack push:myString];            // stack size = 1NSString *anotherString = @"hello universe";[myStack push:anotherString];       // stack size = 2NSString *topMostStackObject; topMostStackObject = [myStack pop]; // stack size = 1NSLog("%@",topMostStackObject);topMostStackObject = [myStack pop]; // stack size = 0NSLog("%@",topMostStackObject);

The log output will be:

hello universehello world