2013-04-10 41 views
0

我試圖分裂一個字符串,並將其分成不同的,但我得到了以下錯誤:的Xcode 4 NSRangeException錯誤分割字符串後

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'

代碼:

NSLog(@"%@", strResult); 

    NSArray* LocInfo = [strResult componentsSeparatedByString: @"|"]; 
    NSString* Response1 = [LocInfo objectAtIndex: 0]; 
    NSString* Response2 = [LocInfo objectAtIndex: 1]; 
    NSString* Response3 = [LocInfo objectAtIndex: 2]; 

任何想法?謝謝!

回答

1

您的strResult分爲LocInfo數組,其中只包含兩個元素,並且您試圖訪問第三個元素。

由於您的字符串已經包含1/2或3個NSString s,因此無需再次存儲到NSString中,您可以直接使用它們LocInfo[index]

如果您需要檢查多少字符串根本就沒有使用:[LocInfo count];

+0

是的,我有這樣的正在從Web服務返回的,有時它沒有回傳第三元素的字符串。謝謝! – NCoder 2013-04-10 10:02:07

+0

所以不需要硬編碼索引:3,檢查它的計數是否只有3,然後訪問該元素。 – 2013-04-10 10:03:18

+0

會做!在我允許的情況下,我會接受你的回答作爲答案。 – NCoder 2013-04-10 10:03:59