I have these lines to read a file and split its lines into items of an array:
- (NSArray *)lerLinhasArquivoBundle:(NSString *)nomeArquivo {
NSString *arquivo = nil;
NSError *error = nil;
NSString *bd = [[NSBundle mainBundle] pathForResource:nomeArquivo ofType:@"csv"];
if (bd) {
arquivo = [NSString stringWithContentsOfFile:bd
encoding:NSUTF8StringEncoding
error:&error];
}
if (error || !bd) {
return nil;
}
return [arquivo componentsSeparatedByString: @"\r\n"];
}
the problem is that this will only work with files that have "windows" CR/LF endings and will fail for files with UNIX line endings. When the file is a UNIX one, I get just one big item on the array.
OK, I can hack the method to test for \r\n
and just \n
and use the one that gives me more items on the array, but that appears to be a lame solution.
Is there a way to know what line endings is being used and use that information on the return line to split the elements into the array?
Use the [NSCharacterSet newlineCharacterSet]
rather than an explicit string:
return [arquivo componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];