On Dec 19, 2008, at 1:22 PM, Steve Wetzel wrote:

I am new to this list and new to mac programming as well. I am working on implementing a stack as a category of NSMutableArray. I want this stack to be able to store objects. This is what I have so far:

//
//  Stack.h
//  Stack implements a basic stack object in an NSMutableArray object.

#import <Foundation/Foundation.h>

@interface NSMutableArray (Stack)
-(void)push:(id)obj;                    //push obj of on the stack
-(id)pop;                                               //pop top item off the 
stack
-(id)peek;                                              //look at the top item 
on the stack
-(void)clear;                                   //remove all objects from the 
stack
-(NSUInteger)size;                              //return the number of items on 
the stack
@end

If I were doing this, I would actually create an object (subclass of NSObject) that would contain an NSMutableArray as an attribute. That way, your API would be very clean.

What you have above would allow users to call any of the NSArray* suite of APIs in addition to yours above. Sometimes too many APIs on an object can lead to issues.

My question involves storing objects on the stack. As I understand it when I store an object on the stack, I am simply storing a pointer to the object on the stack. If I create an NSString object called foo and do the following:

NSString *foo = [[NSString alloc] initWithString:@"foo text"];
[FractionStack push:foo];

I have put a copy of the pointer to foo on the stack. If I now change foo, the top element on the stack changes also. I do not want this to happen but I am not sure as to the best approach to make sure this does not happen.

In this specific case, you cannot change foo since NSString is immutable. If you find yourself adding (pushing) items that are immutable, it would be best to make a copy or mutable copy as needed.

Also, I am thinking I likely will need to release these objects when I pop them and when I clear the stack. Is that correct?

Just read up more on the memory management rules. You can also decide on object-ownership rules. Typically, the container objects retain objects added to them. Then release them when removed. That's all you should be concerned about. It's then up to the original owner of the object to do the right thing.

___________________________________________________________
Ricky A. Sharp         mailto:rsh...@instantinteractive.com
Instant Interactive(tm)   http://www.instantinteractive.com



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to