NSMutableArray is the equivalent of a pop array

If I want to pull the last element from my NSMutableArray , will this be the most correct way?

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

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

+4
source share
3 answers

Save it, delete, use, release.

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

There is no default equivalent for NSMutableArray , but I think you can easily add a category to it to pop up to. Something like this is possible:

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 as follows:

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

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

This will save you a few keystrokes.

If you want to be able to call it one line of code, you can transfer all this to a function or category on NSMutableArray .

+1
source

All Articles