2009-11-03 75 views
0

我有一个的NSMutableArray:NSMutable阵列

NSMutableArray *temp = //get list from somewhere. 

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

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

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

但是我在if语句中声明该索引超出了界限时得到了异常。

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

回答

13

你不能在NSArray中有'空'的插槽。如果[myArray count] == 2即数组有两个元素,那么您肯定知道索引0处有一个对象,索引1处有一个对象。情况总是如此。

+3

继续这个思路,objectAtIndex:永远不能返回零。数组中不能有nil对象,并且在数组外部请求某些东西会引发异常。 – 2009-11-03 14:19:18

+1

我猜你可以..只是通过填充NSNull对象;) – prakash 2009-11-03 14:31:37

+0

+1为“你不能有空插槽” – bpapa 2009-11-03 15:29:59

4

使用count方法首先检查长度。

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

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

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

- (NSUInteger)count 

int arrayEntryCount = [temp count]; 
2

你可以做到这一点的方法:

当初始化,这样做:

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]; 
} 
+2

你*可以*这样做,但你为什么要这么做? – 2009-11-03 14:40:40

+1

有很多情况下,“空占位符”在数组中很有用。 Prakash在说可以向数组中添加[NSNull null]是正确的。 在一种情况下,我必须解决,位置相关的数值数组可能会有“缺失值”。 “缺失值”与[NSNumber numberWithInt:0]不一样... – 2009-11-04 17:00:25

-2

首先你检查返回数组

长度

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

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

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

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

}