Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the first element of an array in Objective C?

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?

like image 364
ojreadmore Avatar asked Jun 17 '09 21:06

ojreadmore


People also ask

How do I remove the first element from an array?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do I remove a specific part of an 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.

How do I remove the first element?

The shift() method removes the first item of an array. The shift() method changes the original array.

How do you delete the first and last elements of an 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.


2 Answers

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.

  • Move memory
  • Duplicate structures
  • Allocate sparsely populated memory blocks
  • Inner loops
  • ... (There are lots more, but my C-life is rusty and, as I said, I'm anti-optimization)

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.

like image 157
Bill K Avatar answered Sep 20 '22 18:09

Bill K


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.

like image 41
Jeffrey Hantin Avatar answered Sep 17 '22 18:09

Jeffrey Hantin