繁体   English   中英

NSMutable阵列

[英]NSMutable Array

我有一个NSMutableArray:

NSMutableArray *temp = //get list from somewhere.

现在有一个方法objectAtIndex,它以指定的索引返回对象。

我想做的是,我首先要检查指定索引处的对象是否存在。 如果存在,那么我想获取该对象。 就像是:

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

但是我在if语句中说该索引超出范围时出现异常。

请任何人告诉我如何实现这一目标。

您在NSArray中不能有“空”插槽。 如果[myArray count] == 2,即array有两个元素,则可以确定在索引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和<count

返回接收器中当前对象的数量。

- (NSUInteger)count

int arrayEntryCount = [temp count];

首先,您检查数组的长度-

NSMutableArray * temp = //从某处获取列表。

现在检查-如果(临时长度){

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

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

}

暂无
暂无

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

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