Does the iOS SDK provide queues and stacks?

后端 未结 8 1728
情话喂你
情话喂你 2021-02-02 08:05

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 m

8条回答
  •  粉色の甜心
    2021-02-02 08:11

    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 
    
    @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
    

提交回复
热议问题