tags:

views:

52

answers:

4

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?

+1  A: 

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.

Michael W.
+1  A: 

Yes, an NSMutableArray doubles as a stack or queue. (It would be slightly inefficient as a queue.)

You could also use C++'s stack and queue adapter, but it makes memory management a bit messy if you want to store Objective-C objects with it.

KennyTM
A: 

No. You missed nothing. That's all. Objective-C is higher level language look like C. Low level control is not required.

Cocoa classes are designed easier use than efficiency. If you want to deal with performance, you have an option of raw C implementation (C standard lib or CoreFoundation). Otherwise, just use easy way. Of course, early-optimization is evil.

If you want a kind of encapsulation, just make a new class which contains NSMutableArray within it. Hide inner NSMutableArray and just expose what you want. But you'll realize this is unnecessary.

Eonil
Thanks. It's code duplication I'm worried about, rather than encapsulation.
Tommy Herbert
A: 

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 {
    NSUInteger count = [contents count];
    if (count > 0) {
        id returnObject = [[contents objectAtIndex:count - 1] retain];
        [contents removeLastObject];
        return [returnObject autorelease];
    }
    else {
        return nil;
    }
}

@end
Tommy Herbert