2011-05-29 42 views
1

我有一個問題。如果objectAtIndex:x爲空,我會得到一個錯誤。在我的代碼中,用戶必須插入由「/」分隔的代碼,例如32/31/43或甚至32 // 12。一切正常,但如果用戶在沒有「/」的情況下插入單個數字,我得到了圖片中顯示的錯誤,但我希望獲得一個警告視圖,告訴用戶代碼已被插入的格式不正確。我希望這很清楚。謝謝 enter image description hereNSArray - objectAtIndex:

回答

2

可能最好的方法是在創建它之後檢查你的數組,以確保有3個值。

NSArray *componentDepthString = [depthString componentsSeperatedByString:@"/"]; 
if ([componentDepthString count] == 3) { 
    // everything is good and you can continue with your code; 
    // rest of the code; 
} else { 
    // the user input bad values or not enough values; 
    UIAlertView *myAlert = [[UIAlertView alloc] 
            initWithTitle:@"can't continue" 
            message:@"user input bad values" 
            delegate:self 
            cancelButtonTitle:@"Cancel" 
            otherButtonTitles:nil]; 
    [myAlert show]; 
    [myAlert release]; 
} 

編輯:你必須編輯標題和消息說你想要什麼,但這是就如何檢查錯誤以及如何顯示警告之前壞數據的基本理念。你將不得不添加自己的邏輯如何與用戶來處理它

2

您可以

[componentDepthString count] 

在你走之前盲目地捅到陣列測試的陣列中的元件數量,確保陣列有,你就需要儘可能多的元素:

// probably a bad idea to name the array with the word "string in it 
NSArray *componentDepths = [depthString componentsSeparatedByString:@"/"]; 
NSInteger numComponents = [componentDepths count]; 

if(numComponents < 3) { 
    // show an alert... 

    return; 
} 

// otherwise proceed as before 
0

字符串「2」 componentsSeparatedByString將返回一個數組只有一個對象:字符串「2」。

您正在嘗試讀取索引爲1的對象(即第二個對象),但該數組只有一個對象。嘗試讀取超出NSArray末尾的值是錯誤的。

看來你要做的是要求輸入的值有兩個'/',所以爲什麼不先檢查一下?

if ([componentDepthString count] != 3) { 
    // show an alert and return 
}