0

我有一个包含一堆字符串的文件,如下所示:

 item1,01-SR,admin,Missing or broken,undefined, 16/04/2013 18:10:10;
 item1,03-SR,admin,In Use,undefined, 16/04/2013 18:10:34;
 item1,01-SR,admin,In Use,undefined, 16/04/2013 18:10:45;
 item1,02-SR,admin,In Use,undefined, 16/04/2013 18:10:49;
 item1,05,admin,In Use,undefined, 16/04/2013 18:10:56;

我正在读取字符串,然后将它们拆分,所以我一次只得到一个字符串。然后我想再次拆分我得到的字符串,所以每个 CSV 都是它自己的变量。我已经尝试过这样(numLines 是文件中行数的计数):

 while (count1 < numLines) {
      NSString *message = [[strings objectAtIndex: count1] copy];

      NSMutableArray *items = [[fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@";"]] mutableCopy];

      NSString *items1 = [[items objectAtIndex: count1] copy];

      NSLog(@"items: %@", items1);

      NSMutableArray *inditems = [[items1 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]] mutableCopy];

      NSString * item1 = inditems[0];
      NSString * bnum1 = inditems[1];
      NSString * user1 = inditems[2];
      NSString * state1 = inditems[3];
      NSString * gender1 = inditems[4];
      NSString * tstamp1 = inditems[5];

      NSLog(@"item: %@", item1);
      NSLog(@"bnum: %@", bnum1);
      NSLog(@"user: %@", user1);
      NSLog(@"state: %@", state1);
      NSLog(@"gender: %@", gender1);
      NSLog(@"tstamp: %@", tstamp1);

      count1++;
}

现在,这可以从文件中选择一行并将前两项放入数组中,然后将 item1 和 bnum1 的值写入日志,但随后由于某种原因引发异常。现在这通常会向我暗示数组中不存在第 2 项,所以我做了这样的计数:

 NSLog(@"count = %d", [inditems count]);

哪个正确返回 6。然后我想检查它是否真的可以从数组中读取另一个项目,所以我做了:

 NSString *tstamp1 = [[inditems lastObject] copy];

正确记录时会返回如下时间戳:

 16/04/2013 18:10:10

所以我认为“哦,至少第 5 项有效”并尝试获取该项目:

 while (count1 < numLines) {
      NSString *message = [[strings objectAtIndex: count1] copy];

      NSMutableArray *items = [[fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@";"]] mutableCopy];

      NSString *items1 = [[items objectAtIndex: count1] copy];

      NSLog(@"items: %@", items1);

      NSMutableArray *inditems = [[items1 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]] mutableCopy];

      NSString * item1 = inditems[0];
      NSString * bnum1 = inditems[1];
      NSString * tstamp1 = inditems[5];

      NSLog(@"item: %@", item1);
      NSLog(@"bnum: %@", bnum1);
      NSLog(@"tstamp: %@", tstamp1);

      count1++;
}

但这也会引发异常!我可能在这里做一些愚蠢的事情,但我会很感激任何帮助。

谢谢!

4

1 回答 1

0

我的猜测是您的 NSArray *strings 包含导致错误的空值。你需要先检查它,然后再做你的逻辑。

//path is your file path
NSString* fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *strings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (int i = 0; i < [strings count]; i++){
   if (![[strings objectAtIndex:i] isEqualToString:@""]){
   //Here do your code...
   }
}
于 2013-04-17T08:48:51.213 回答