Click here to Skip to main content
11,640,788 members (61,503 online)
Click here to Skip to main content

Tagged as

How to implement a stack in Objective-C

, 23 Jul 2011 CPOL 28.9K 6
Rate this:
Please Sign up or sign in to vote.
Stack implementation for Objective-C.

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Cloud Hsu
Architect LPI
Taiwan Taiwan
CloudBox cross-platform framework. (iOS+ Android)
Github: cloudhsu
My APP:
1. Super Baby Pig (iOS+Android)
2. God Lotto (iOS+Android)
2. Ninja Darts (iOS)
3. Fight Bingo (iOS)

You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 5 kl;\ Pin
Ameen Abudbush30-Jul-11 18:32
memberAmeen Abudbush30-Jul-11 18:32 
BugObject-C? Pin
AspDotNetDev18-Jul-11 11:46
mvpAspDotNetDev18-Jul-11 11:46 
BugA bug? Pin
xesique17-Jul-11 21:15
memberxesique17-Jul-11 21:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150731.1 | Last Updated 23 Jul 2011
Article Copyright 2011 by Cloud Hsu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid