简体   繁体   English

NSMutable阵列

[英]NSMutable Array

I have a NSMutableArray: 我有一个NSMutableArray:

NSMutableArray *temp = //get list from somewhere.

Now there is one method objectAtIndex which returns the object at specified index. 现在有一个方法objectAtIndex,它以指定的索引返回对象。

What I want to do is that, I want to first check whether an object at specified index exists or not. 我想做的是,我首先要检查指定索引处的对象是否存在。 If it exists than I want to fetch that object. 如果存在,那么我想获取该对象。 Something like: 就像是:

if ([temp objectAtIndex:2] != nil)
{
     //fetch the object
}

But I get exception at the if statement saying that index beyond bound. 但是我在if语句中说该索引超出范围时出现异常。

Please anyone tell me how to achieve this. 请任何人告诉我如何实现这一目标。

you cannot have 'empty' slots in an NSArray. 您在NSArray中不能有“空”插槽。 If [myArray count]==2 ie array has two elements then you know for sure that there is an object at index 0 and an object at index 1. This is always the case. 如果[myArray count] == 2,即array有两个元素,则可以确定在索引0有一个对象,在索引1有一个对象。情况总是如此。

Check the length first using the count method. 首先使用计数方法检查长度。

if ([temp count] > indexIWantToFetch)
    id object = [temp objectAtIndex:indexIWantToFetch];

you could do this way: 您可以这样做:

When you initialize, do something like: 初始化时,请执行以下操作:

NSMutableArray *YourObjectArray = [[NSMutableArray alloc] init];
for(int index = 0; index < desiredLength; index++)
{
   [YourObjectArray addObject:[NSNull null]];
}

Then when you want to add but check if it already exists, do something like this: 然后,当您要添加但检查它是否已经存在时,请执行以下操作:

YourObject *object = [YourObjectArray objectAtIndex:index];
if ((NSNull *) object == [NSNull null]) 
{
    /// TODO get your object here..

    [YourObjectArray replaceObjectAtIndex:index withObject:object];
}

Just check that the index is >= 0 and < count 只需检查索引是否> = 0和<count

Returns the number of objects currently in the receiver. 返回接收器中当前对象的数量。

- (NSUInteger)count

int arrayEntryCount = [temp count];

First of all you check the length of array- 首先,您检查数组的长度-

NSMutableArray *temp = //get list from somewhere. NSMutableArray * temp = //从某处获取列表。

now check- if(temp length) { 现在检查-如果(临时长度){

Your objectclass *obj = [temp objectAtIndex:indexnumber]; 您的对象类* obj = [temp objectAtIndex:indexnumber];

// indexnumber is 0,1,2 ,3 or anyone... // indexnumber是0,1,2,3或任何人...

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM