Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 505
Jacksonkr Avatar asked Jun 11 '12 19:06

Jacksonkr


2 Answers

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

id theObject = [[myMutableArray lastObject] retain];
[myMutableArray removeLastObject];
//use theObject....
[theObject release];
like image 73
Firula Avatar answered Oct 19 '22 01:10

Firula


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];
like image 28
Alladinian Avatar answered Oct 19 '22 01:10

Alladinian