NSMutableArray - array pop equivalent

If I want to pop the last item from my NSMutableArray would this be the most proper way?

id theObject = [myMutableArray objectAtIndex:myMutableArray.count-1];
[myMutableArray removeLastObject];

I'm sure someone from SOF has a better way.


Retain it, delete it, use it, release it.

id theObject = [[myMutableArray lastObject] retain];
[myMutableArray removeLastObject];
//use theObject....
[theObject release];

There is no pop equivalent for NSMutableArray but I guess you could easily add a category to it for popping. Something like this perhaps:


@interface NSMutableArray (Queue)


#import "NSMutableArray+Queue.h"

@implementation NSMutableArray (Queue)
    id obj = [[[self lastObject] retain] autorelease];
    [self removeLastObject];
    return obj;

Then import it and use it like this:

#import "NSMutableArray+Queue.h"
id lastOne = [myArray pop];

You can use lastObject to get the last object in the array.

That would save you a few keystrokes.

If you want to be able to call it with a single line of code, you can wrap it all in a function or a category on NSMutableArray.

Need Your Help

How does the Graphics Class in Java work?

java swing graphics paintcomponent

Recently, I have been trying to do some Java work with graphics. Now the Graphics class is abstract, meaning it itself cannot be instantiated but a subclass of it might be able to be instantiated....