从文本文件中读取时出现iOS线程错误

时间:2012-04-06 18:34:01

标签: ios multithreading nsarray text-files sigabrt

我正在尝试从文本文件中打印数组的单个元素,这是我正在使用的代码:

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

提前感谢您的帮助!

1 个答案:

答案 0 :(得分: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
          ]);
相关问题