NSMutableArray在索引处插入对象 [英] NSMutableArray insert object at index

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

问题描述

我有一个空的可变数组.例如,是否可以在索引2处插入对象,而索引0和1处什么也没有?我的意思是动态增加容量或类似的功能. .

I have an empty mutable array. Is it possible to insert object at index 2 for example, while there's nothing at index 0 and 1? I mean to increase capacity dynamically or something like that. .Regards.

推荐答案

NSMutableArray不是稀疏数组;它不允许以后可以填充的空插槽. initWithCapacity:只是提示数组将被填充到一定数量;在实践中通常不需要这样做,除非您确切知道要在数组中推入多少项,否则不要打扰它(只需使用init).

NSMutableArray is not a sparse array; it does not allow empty slots that can be filled in later. initWithCapacity: just hints to the array that it will be filled to a certain amount; it isn't generally necessary in practice and, unless you know exactly how many items you are going to shove in the array, don't bother calling it (just use init).

可变数组会随着对象的添加而有效地增长.

A mutable array will quite efficiently grow in size as objects are added.

如果您需要支持空洞"的数据结构,则可以使用其他方法或在应该为空的插槽中放置一个占位符对象.

If you need a data structure that supports "holes", then either use something else or put a placeholder object in the slots that are supposed to be empty.

即如果您想要一个具有10个插槽的阵列,则可以这样做:

I.e. if you wanted an array with 10 slots, you might do:

NSMutableArray *a = [NSMutableArray array];
for(int i = 0; i<10; i++) [a addObject: [NSNull null]];

然后可以检查检索到的对象isEqual: [NSNull null]是否知道插槽是否为空.而且,您可以使用replaceObjectAtIndex:withObject:将对象粘贴到特定索引处.

You can then check if the retrieved object isEqual: [NSNull null] to know if the slot is empty or not. And you can use replaceObjectAtIndex:withObject: to stick an object at a specific index.

或者您可以使用其他数据结构;例如,以索引为键的字典会起作用.

Or you could use a different data structure; a dictionary with the indices as the keys would work, for example.

这篇关于NSMutableArray在索引处插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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