objective-cxcodearraysfor-loopnsmutablearray

Replace, move objects in NSMutableArray


I Have an array which I have already set the capacity to 5. What I want to do is, when I add an object and the capacity exceeds 5 then it moves the whole array structure of objects by one. For example 1,2,3,4,5 (array). Then when 6 comes to be added It must replace 5 and delete one to result in 2,3,4,5,6 and so on.. So in other words it has to save only last 5 objects. BUT as in the actual coding it will save objects with coordinates in an array with capacity of 100+ so it has to be quick and efficient. I tried with int to see how it progresses:

      NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];

            int i;
            for (i = 0; i<=20;i++ ) {
                NSNumber *number = [NSNumber numberWithInt:i];
                if (i>=5) {
                [array insertObject:number atIndex:5];
                }else{
                [array addObject:number];
                }
                NSLog(@"array = %@, count = %i",array, array.count);
            }

but it stores all 20 in sorting like 1,2,3,4,20,19,18,17...6 any help would be appreciated! Thank you in advance..


Solution

  • If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room. so what you can use is replaceObjectAtIndex:withObject: this will replace the object. but if you want to remove the first object you do it your self. first check the length of the array. if greater than 5 remove the first element and shift all the objects to the the lower index. then add the new object.

    if ([array count]>=5)
    {
    [array removeObjectAtIndex:index];
    
    [array insertObject:new object atIndex :5];