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 - 第三行被注释掉以防我以后想使用它......所以不用担心。

提前感谢您的帮助!

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 回答