2012-04-06 60 views
0

我試圖打印從文本文件的數組的單個元素,這裏是我使用的代碼:從文本文件讀取時的iOS線程錯誤

//Tells the compiler where the text file is and its type 
NSString* path = [[NSBundle mainBundle] pathForResource:@"shakes" 
               ofType:@"txt"]; 


//This string stores the actual content of the file 
NSString* content = [NSString stringWithContentsOfFile:path 
               encoding:NSUTF8StringEncoding 
               error:NULL]; 


//This array holds each word separated by a space as an element 
NSArray *array = [content componentsSeparatedByString:@" "]; 



//Fast enumeration for loop tha prints out the whole file word by word 
// for (NSString* word in array) NSLog(@"%@",word); 


//To access a certain element in an array 
NSLog(@"%@", [array objectAtIndex:3 
       ]); 

的問題是 - 如果我希望訪問前兩個元素,0或1,這很好。但是,只要我想訪問說,元件2或3,我得到以下錯誤:

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

這是一個SIGABRT線程錯誤 - 這似乎裁剪很多iOS的編程,但它通常相當可解。

文本文件「Shakes.txt」爲6個元素,僅用於測試目的。

PS - 第三行被註釋掉,之後我想稍後使用它......所以不要擔心這一點。

在此先感謝您的幫助!

回答

0

基本上你試圖訪問一個超出數組範圍的對象。 日誌非常明顯,你的數組只有1個元素,並且你正在嘗試訪問第4個元素。

將此添加到您的代碼中。

NSMutableArray *contentArray = [[NSMutableArray alloc] init]; 

    for (NSString* word in array) 
    { 
    [contentArray addObject:word] 
    } 

    //Now try to access contentArray 

    NSLog(@"%@", [contentArray objectAtIndex:3 
      ]); 
+0

我意識到了這一點,它實際上可以讓我訪問數組的2種元素 - 0和1。不知道如何解決,雖然它 - 在文本文件中的數組有6個元件。 – 2012-04-06 18:38:25

+0

如果是這樣,那麼你的內容沒有正確地從你的文本文件中獲取元素你試過NSLogging你的內容? – 2012-04-06 18:40:28

+0

是的,代碼的第三位 - 我註釋掉的那個代碼打印出的數組很好,所有元素。 – 2012-04-06 18:44:00