使用代码块和函数式编程习惯对逗号分隔值 (CSV) 文件进行解析的实用程序。
特点
将头文件包含在您的代码中
#import <MMPCSVUtil/MMPCSVUtil.h>
读取 CSV 的最简单方法是简单地读取所有记录作为 NSArray。每条记录都会是 NSArray,所以以下示例的结果是一个包含 NSArrays 的 NSArray
NSArray *allRecords = [[MMPCSV readURL:[[NSBundle mainBundle] URLForResource: @"test1" withExtension:@"csv"]]
all];
NSLog(@"CSV has %lu records", [allRecords count]);
为了为较大的 CSV 文件节省内存,最好在解析器解析文件的同时直接与之交互,通过指定将要被调用的 each
代码块来处理解析器产生的每条记录。以下示例说明了如何获得解析器完成字段和记录解析的通知
[[[MMPCSV readURL:[[NSBundle mainBundle] URLForResource: @"test1" withExtension:@"csv"]]
field:^(id field, NSInteger index) {
NSLog(@"%ld, %@", index, field);
}]
each:^(NSArray *record, NSUInteger index) {
NSLog(@"%ld: %@", index, record);
}];
如果 CSV 文件的第一行是标题,则可以使用标题的值作为记录的键。当使用 useFirstLineAsKeys
来自定义格式,如下例所示时,传递给 each
代码块的记录将是一个 NSDictionary。
[[[MMPCSV readURL:[[NSBundle mainBundle] URLForResource: @"test2" withExtension:@"csv"]]
format:[[MMPCSVFormat defaultFormat] useFirstLineAsKeys]]
each:^(NSDictionary *record, NSUInteger index) {
NSLog(@"%ld: title: %@", index, [record objectForKey:@"title"]);
}];
以下示例说明如何:
error
处理错误;begin
在解析器开始时发出通知,并可选地处理标题;map
将解析器的记录输出映射到任何对象;filter
过滤解析器产生的记录。[[[[[[[MMPCSV readURL:[[NSBundle mainBundle] URLForResource: @"test2" withExtension:@"csv"]]
format:[[[MMPCSVFormat defaultFormat]
useFirstLineAsKeys]
sanitizeFields]]
error:^(NSError *error) {
NSLog(@"error: %@", error);
}]
begin:^(NSArray *header) {
NSLog(@"header: %@", header);
}]
map:^NSString *(NSDictionary *record) {
return [record objectForKey:@"title"];
}]
filter:^BOOL(NSString *title) {
return [title length] > 10;
}]
each:^(NSString *longTitle, NSUInteger index) {
NSLog(@"%ld: %@", index, longTitle);
}];
请注意,map
会在 filter
之前执行,因此传递给 filter
的对象类型将是 map
返回的类型。
目前不可用,但我会在更新库时编写文档。
MMPCSVUtil 由Mamad Purbo维护
MMPCSVUtil 在 MIT 许可下可用。有关更多信息,请查看 LICENSE 文件。
此库使用从 CHCSVParser(https://github.com/davedelong/CHCSVParser)改编的代码。版权所有 (c) 2014 Dave DeLong