2009-11-03 79 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或任何人...

}