我有一个带有大量字符串的文件,如下所示:
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++;
}
但这也引发了异常!我可能在这里做了一些愚蠢的事情,但我会感激任何帮助。
谢谢!
答案 0 :(得分:0)
我的猜测是你的NSArray *字符串包含空值,导致你的错误。你需要先检查它,然后再做你的逻辑。
//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...
}
}