Does the iOS SDK provide queues and stacks?

后端 未结 8 1738
情话喂你
情话喂你 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:24

    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:

    NSMutableArray+Stack.h

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

    NSMutableArray+Stack.m

    #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 = 0
    
    NSString *aString = @"hello world";
    [myStack push:myString];            // stack size = 1
    
    NSString *anotherString = @"hello universe";
    [myStack push:anotherString];       // stack size = 2
    
    NSString *topMostStackObject; 
    
    topMostStackObject = [myStack pop]; // stack size = 1
    NSLog("%@",topMostStackObject);
    
    topMostStackObject = [myStack pop]; // stack size = 0
    NSLog("%@",topMostStackObject);
    

    The log output will be:

    hello universe
    hello world
    

提交回复
热议问题