Stack is a very commonly used data structure. But Objective-C does not have this data structure. So I use NSMutableArray
to implement the basic functions push and pop.
HsuStack.h
@interface HsuStack : NSObject {
NSMutableArray* m_array;
int count;
}
- (void)push:(id)anObject;
- (id)pop;
- (void)clear;
@property (nonatomic, readonly) int count;
@end
HsuStack.m
#import "HsuStack.h"
@implementation HsuStack
@synthesize count;
- (id)init
{
if( self=[super init] )
{
m_array = [[NSMutableArray alloc] init];
count = 0;
}
return self;
}
- (void)dealloc {
[m_array release];
[self dealloc];
[super dealloc];
}
- (void)push:(id)anObject
{
[m_array addObject:anObject];
count = m_array.count;
}
- (id)pop
{
id obj = nil;
if(m_array.count > 0)
{
obj = [[[m_array lastObject]retain]autorelease];
[m_array removeLastObject];
count = m_array.count;
}
return obj;
}
- (void)clear
{
[m_array removeAllObjects];
count = 0;
}
@end
Objective-C has a type called id, that acts in some ways like a void*, though it's meant strictly for objects. Objective-C differs from Java and C++ in that when you call a method on an object, it doesn't need to know the type. That method simply just has to exist. This is refered to as message pasing in Objective-C.