2012-03-15 104 views
15

noobie問題..什麼是檢查NSArray或NSMutableArray的索引是否存在的最佳方法是什麼?我到處搜索無濟於事!NSArray越界檢查

這是我曾嘗試:

if (sections = [arr objectAtIndex:4]) 
{ 
    /*.....*/ 
} 

sections = [arr objectAtIndex:4] 
if (sections == nil) 
{ 
    /*.....*/ 
} 

但兩者拋出不允許的「越界」的錯誤我繼續

(不回覆嘗試趕上,因爲那不是一個解決方案對我來說)

在此先感謝

回答

14
if (array.count > 4) { 
    sections = [array objectAtIndex:4]; 
} 
+1

媽..即時通訊這麼愚蠢。當然的!數組按順序填充。我把我的頭弄得一團糟。謝謝隊友+1 – spacebiker 2012-03-15 07:19:39

+3

我認爲objective-c語言在這裏有點愚蠢。如果'[array objectAtIndex:outOfBounds]'返回'nil'而不是崩潰,我會更加舒服。 – turingtested 2016-05-24 10:20:04

0

記住的NSArray是順序0到N-1項目

你正在努力accessitem超出限制arraynil那麼編譯器會扔出bound error

編輯:@ sch上面的答案顯示了我們如何檢查NSArray是否需要存在或不存在有序物品。

+0

N件物品的排列順序從0到N-1 – tothemario 2015-03-24 21:27:07

+0

@tothemario:美妙的捕捉。謝謝 – 2015-03-25 07:11:55

2

如果你有一個整數索引(例如i),通常可以防止此錯誤通過檢查數組邊界這樣

int indexForObjectInArray = 4; 
NSArray yourArray = ... 

if (indexForObjectInArray < [yourArray count]) 
{ 
    id objectOfArray = [yourArray objectAtIndex:indexForObjectInArray]; 
} 
0

可以使用MIN運營商失敗默默這樣[array objectAtIndex:MIN(i, array.count-1)],要麼獲取數組中的下一個對象或最後一個對象。可能是有用的,當你如想連接字符串:

NSArray *array = @[@"Some", @"random", @"array", @"of", @"strings", @"."]; 
NSString *concatenatedString = @""; 
for (NSUInteger i=0; i<10; i++) { //this would normally lead to crash 
    NSString *nextString = [[array objectAtIndex:MIN(i, array.count-1)]stringByAppendingString:@" "]; 
    concatenatedString = [concatenatedString stringByAppendingString:nextString]; 
    } 
NSLog(@"%@", concatenatedString); 

結果:「字符串的一些隨機排列。。。」