Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift all elements in an NSMutableArray?

I have an NSMutableArray that will start with 0 objects in it, but as the program progresses objects will be added to it. How can I shift all elements down, when a new element is added?

For example:

1) NSMutableArray array = 0 elements

2) NSMutableArray array = 1 element { [0,a]}

3) NSMutableArray array = 2 elements {[0, b], [1,a]}

4) NSMutableArray array = 3 elements {[0,c],[1,b],[2,c]}

As can be seen through the above list as objects are added to the array, all current elements move down. However, I do not want my array to exceed a certain size (lets say 10 elements). When a element is pushed to 11 I want it "pushed" out of the array. How can I go about doing this?

Similar questions: NSMutablearray move object from index to index

like image 539
fdh Avatar asked Aug 24 '26 07:08

fdh


1 Answers

You can do that like this:

[array insertObject:object atIndex:0];
if ([array count] > 10) {
    [array removeLastObject];
}

The first line will automatically push the other elements out of the way, and the next bit just makes sure the array's length never exceeds 10.

like image 95
Alexis King Avatar answered Aug 26 '26 06:08

Alexis King