0

テキストファイルから配列の個々の要素を出力しようとしています。使用しているコードは次のとおりです。

//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
              ]);  

問題は、最初の 2 つの要素 (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 - 3 行目は、後で使用する場合に備えてコメント アウトされています...だから心配しないでください。

助けてくれてありがとう!

4

1 に答える 1

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
          ]);
于 2012-04-06T18:36:21.483 に答える