替换,在NSMutableArray中移动对象 [英] Replace, move objects in NSMutableArray

查看:264
本文介绍了替换,在NSMutableArray中移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我已经设置了容量为5阵列。
我想要做的是,当我添加对象和容量超过5然后由一个移动的物体的全阵列结构。例如1,2,3,4,5(阵列)。然后,当6来加它必须更换5和删除一个导致2,3,4,5,6等。所以,换句话说,它具有节省仅最后5个对象。但由于在实际的编码会被保存在与100+容量的阵列坐标对象,所以它必须是快速,高效。
我与诠释想看看它是如何进展:

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);
            }

但它存储所有20分拣像1,2,3,4,20,19,18,17 ...... 6任何帮助将是AP preciated!谢谢你在前进。

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..

推荐答案

如果索引已被占用,该物体在索引及以后是通过将1至其索引,以腾出空间移位。
所以你可以使用 replaceObjectAtIndex:withObject
这将替换的对象。但如果你想删除的第一个对象,你做你的自我。
首先检查数组的长度。如果大于5移除第一元件和所有的对象转移到下索引。然后添加新的对象。

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];

这篇关于替换,在NSMutableArray中移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆