In Objective C, is there a one-liner or something small to remove (shorten by one) and return the first element of an array, regardless of its index?
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array. The following implementation shows removing the element from an array using ArrayList.
The shift() method removes the first item of an array. The shift() method changes the original array.
To remove the first and last elements from an array, call the shift() and pop() methods on the Array. The shift method removes the first and the pop method removes the last element from an array. Both methods return the removed elements.
That would be a poor thing to do.
Objective-C on the iPhone can actually use most of the performance perks of C.
If you look at some of my other posts, you'll see I'm ADAMANTLY against premature optimization, but when you are coding at the C level, there are just some things you don't do unnecessarilly.
What you probably want is a well-implemented queue. Something that pre-allocates a large enough circular memory structure and then has two pointers that track the first and last bytes.
I'd be pretty surprised to hear that Objective-C didn't have a queue data structure.
Also, don't strive for the one-liners. All the stuff about terse code is overrated. If it makes more sense to call a method, so be it.
I don't know of a method that returns the item removed, but you can do this using a combination of NSArray#objectAtIndex:0
and NSMutableArray#removeObjectAtIndex:0
. I suppose you could introduce a new method category on NSMutableArray
that implements a shift
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With