Search code examples
objective-ccollectionsstackstrong-typing

How to create a typed stack using Objective-C


I can create a stack class quite easily, using push and pop accessor methods to an NSArray, however. I can make this generic to take any NSObject derived class, however, I want to store only a specific class in this stack.

Ideally I want to create something similar to Java's typed lists (List or List) so that I can only store that type in the stack. I can create a different class for each (ProjectStack or ItemStack), but this will lead to a more complicated file structure.

Is there a way to do this to restrict the type of class I can add to a container to a specific, configurable type?


Solution

  • You can try something like this, although I do not recommend it:

    @interface TypedMutableStack : NSObject {
       Class type;
    @private
       NSMutableArray *internal;
    }
    
    - (id) initWithType:(Class) type_;
    
    @end
    
    #define CHECK_TYPE(obj) if(![obj isKindOfClass:type]) {\
          [NSException raise:NSInvalidArgumentException format:@"Incorrect type passed to TypedMutableStack"];\
     }
    
    
    @implementation TypedMutableStack
    
    - (void) dealloc {
      [internal release];
      [super dealloc];
    }
    
    - (id) initWithType:(Class) type_ {
       self = [super init];
       if(self) {
          type = type_;
          internal = [[NSMutableArray alloc] init];
       }
       return self;
    }
    
    - (void) addObject:(id) obj {
       CHECK_TYPE(obj);
       [internal addObject:obj];
    }
    
    - (void) replaceObjectAtIndex:(NSUInteger) index withObject:(id) obj {
        CHECK_TYPE(obj);
        [internal replaceObjectAtIndex:index withObject:obj];
    }
    
    - (void) insertObject:(id) obj atIndex:(NSUInteger) index {
        CHECK_TYPE(obj);
        [internal insertObject:obj atIndex:index];
    }
    
    //...
    @end