我有一个的NSMutableArray:

NSMutableArray *temp = //get list from somewhere.

现在有一种方法,其objectAtIndex在指定的索引返回对象。

我想要做的是,我想先检查在指定的索引的对象是否存在。如果它存在,比我想获取该对象。是这样的:

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

但我在,如果声明称,指数超越界得到例外。

请谁能告诉我如何实现这一目标。

有帮助吗?

解决方案

你不能在一个NSArray“空”的槽。如果[myArray的计数] == 2即阵列具有两个元素,那么你确实知道有在索引0处的对象和索引1的对象这是总是如此。

其他提示

检查第一使用计数方法的长度。

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

你可以做这样的:

在初始化,做这样的事情:

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

然后,当你想添加但检查如果它已经存在,做这样的事情:

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

    [YourObjectArray replaceObjectAtIndex:index withObject:object];
}

只需检查该指数是> = 0和<计数

目前返回在接收器对象的数量。

- (NSUInteger)count

int arrayEntryCount = [temp count];

首先你检查阵列的长度 -

从某处

的NSMutableArray *临时= //获取列表。

现在入住 如果(温度长度) {

您对象类* OBJ = [温度objectAtIndex:indexnumber];

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

}

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top