Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

3 Answers

up vote 8 down vote accepted

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

id theObject = [[myMutableArray lastObject] retain];
[myMutableArray removeLastObject];
//use theObject....
[theObject release];
share|improve this answer
add comment

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

NSMutableArray+Queue.h

@interface NSMutableArray (Queue)
-(id)pop;
@end

NSMutableArray+Queue.m

#import "NSMutableArray+Queue.h"

@implementation NSMutableArray (Queue)
-(id)pop{
    id obj = [[[self lastObject] retain] autorelease];
    [self removeLastObject];
    return obj;
}
@end

Then import it and use it like this:

#import "NSMutableArray+Queue.h"
...
id lastOne = [myArray pop];
share|improve this answer
    
Are you sure you the object it returns should be copied? I would expect to pop the same object off the stack that I put on it. –  Monolo Jun 11 '12 at 19:49
    
@Monolo Thanx man I have updated the answer (if anyone knows though how this could be done under ARC I would be interested). –  Alladinian Jun 11 '12 at 19:58
    
Just get rid of the retain and autorelease messages. ARC should take care of the rest. –  Zev Eisenberg Jan 26 at 3:19
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.